function foo() {
if (arguments.callee.self)
return arguments.callee.self;
arguments.callee.self = this;
//do sth
}
I understand when it’s called like this:
var a = foo();
When foo gets executed, arguments.callee is foo itself. So it passes this to the undefined variable self. Next time when another function calls foo, it returns this. Clearly this will work.
Things seems to get tricker when it’s called like this:
var b = new foo();
What I think is that js engine creates another instance of foo and execute its code. But it seems that it passes back the this reference as self is already defined just like the same instance of foo.
Then what “new” actually does here?
newcalls the function as a constructor. If the target function explicitly returns an object, then that object will returned instead of the just created one.Since you are running this code under non-strict mode, the function explicitly returns the global object after first call, so it won’t return the newly created object with
new foo()