Why my instanceof operator doesn't respond true?
Why my instanceof operator doesn't respond true?
I'm trying out instanceof
operator. I tried out something like this.
instanceof
function f() return f;
new f() instanceof f;
// false
Why this came out to be false
, when these are true
false
true
function f() return f;
new f() instanceof Function;
// true
function f() return f;
new f() instanceof Object;
//true
When tried to save this to a variable still resulted same
function f() return f;
var n = new f();
n instanceof f;
// false
n();
// function f()
n() instanceof f;
// false
n instanceof Function // true
n() instanceof Function // true
Why return f;
statement have changed everything?
What did return f
did to cause this behavior?
return f;
return f
3 Answers
3
First, I'd recommend checking out the article on the new operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new
Specifically, note that
When the code new Foo(...) is executed, the following things happen:
By explicitly returning f
, your are overriding the normal creation process. When you use instanceof
, you are asking "Is n and instance of f". It's not. It is f. It is not an instance of itself.
f
instanceof
Since clearly f
is a function, and n === f
, both will return true when you try to determine if they are functions. Additionally, in Javascript, functions themselves are objects (as are arrays), which is why new f() instanceof Object
is true.
f
n === f
new f() instanceof Object
You are returning f
from your constructor. f
is the constructor. So your constructor is never constructing an instance, you're just always testing whether the constructor is an instance of itself. Which it isn't, by definition.
f
f
By returning f
, you return the function, which is no instance of f
, because it lacks the call with new
.
f
f
new
function f() return f;
console.log(new f() === f);
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.