Javascript confusing syntax inconsistence for null, instanceof and typeof?

前端 未结 3 2017
执念已碎
执念已碎 2020-12-20 08:16
var obj = {};
typeof obj; // returns \"object\"
obj instanceof Object // return true

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


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-20 08:40

    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 status-by-design. 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).

提交回复
热议问题