Rahul Chatterjee
Rahul Chatterjee

Reputation: 29

new instance is not instanceof itself

function f(){
    return f;
}
console.log(new f() instanceof f); 

The snippet above is giving false as output. How can it happen?

Upvotes: 2

Views: 69

Answers (2)

Tushar
Tushar

Reputation: 87203

The function f is returning the reference to itself. Don't return anything from the function. So, by default the function context this will be returned.

new f() will return the reference to f which clearly is not instance of f(itself).

function f() {
    // No need to return anything

    // return this is implicit
}

console.log(new f() instanceof f);

Upvotes: 3

Ski
Ski

Reputation: 14497

f that you are returning is not an instance, it's function/constructor f, instead of return f do return this - this will be instance of f

Upvotes: 2

Related Questions