0
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?

1 Answer 1

3

new calls 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()

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.