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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế