Javascript confusing syntax inconsistence for null, instanceof and typeof?

前端 未结 3 2028
执念已碎
执念已碎 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:51

    That's a common bug of ECMAScript.

    null is not an object, it's a primitive value.(So you can't modify it like adding properties to it)

    typeof null should return null

    typeof null // object (bug in ECMAScript, should be null)

    typeof undefined // undefined

    null === undefined // false

    null == undefined // true

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null

    EDITED

    It's not available to see though

    Changed 3 weeks ago by brendan

    You know, this all came about because of rushing in early May 1995, which led to a leak of type tag representation shared by null and object types. But null means "no object", so it didn't raise hackles until it was too late to fix in Netscape 2, and after that we were loath to "fix" it and "break the web". That argument only applies more in degree of web population now. We have other fish to fry. This one was has been swallowed already. Let's not change typeof null for ES4 and work on more vital issues.

    http://web.archive.org/web/20071110193102/http://bugs.ecmascript.org/ticket/250

    also check this answer

    Why is null an object and what's the difference between null and undefined?

提交回复
热议问题