JavaScript

Tongue Twisting This

Inside a function A, THIS always points to the scope outside the function A. Unless, it gets NEWed. Then THIS would point to the object NEWed out, all the THISes inside of that function A, ┬áinside of the function B that’s inside of the function A, and inside of the function C that’s inside of the function B that’s inside of the function A… Since the this inside of function A is the object, and all the functions inside of function A points to their outer scope, which is the THIS inside of function A.

So the only difference between a = Fn() and b = new Fn() is that their THISes point to different things, and that b gets to be something if Fn doesn’t even return anything. On the other hand, if you call a constructor directly:

function FnX(){
    this.FnY = function(){}
}
FnX()

Since the this with this.FnY is actually window, you get FnY attached as a method to window object. How bizarre. So no one does this.

And if you return something inside of FnX(), NEW would lose its magic, since there’s no object to create or this to bind.

Standard