Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

oop - Javascript confusing syntax inconsistence for null, instanceof and typeof?

var obj = {};
typeof obj; // returns "object"
obj instanceof Object // return true

typeof null // returns "object"
null instanceof Object // returns false

And how about

typeof undefined // return "undefined"
undefined instanceof undefined 
// ERROR:  Uncaught TypeError: Expecting a function in instanceof check, 
//         but got undefined

Why is this the case? I have read a lot about related topics on SO but still can't get this.

Understand that 'typeof' would return a String, so it pretty much reflects the rules in Javascript.(eg. null is a object... well fine..) But why "null instanceof Object" return false ?

"x instanceof y"

Does it mean 'x' has to be created by the 'y' constructor? And for null this is not the case ?

EDIT

Would really appreciate if you could explain the different intention behind instanceof and typeof otherthan then syntax and return value.

Difference between null and undefined

typeof null        // object (bug in ECMAScript, should be null)
typeof undefined   // undefined
null === undefined // false
null  == undefined // true

REF

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It's just the design decision which might be contrived or weird. According to the typeof UnaryExpression if evaluated as the following. I've just included the poin that matters.

ECMA Spec: Return a String determined by Type(val) according to Table 20.

Table 20:
╔═════════════╦══════════╗
║ Type of val ║  Result  ║
╠═════════════╬══════════╣
║ null        ║ "object" ║
╚═════════════╩══════════╝

So, there's nothing we can do about it. It's . But it's correct to return false because, there is a separate type for null called Null type

Null type: type whose sole value is the null value

null isn't an instance of Object, obviously, since it has got it's own type. It's just that typeof operator returns "object". It's got to do with the design of javascript.

Why is it so? Will have to ask Brendan Eich(Founder of Javascript).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...