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

后端 未结 22 1030
猫巷女王i
猫巷女王i 2020-11-22 02:58

Why is null considered an object in JavaScript?

Is checking

if ( object == null )
      Do something

the

22条回答
  •  清酒与你
    2020-11-22 03:39

    From "The Principles of Object-Oriented Javascript" by Nicholas C. Zakas

    But why an object when the type is null? (In fact, this has been acknowledged as an error by TC39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making "object" a logical return value, but that’s still confusing.)

    Zakas, Nicholas C. (2014-02-07). The Principles of Object-Oriented JavaScript (Kindle Locations 226-227). No Starch Press. Kindle Edition.

    That said:

    var game = null; //typeof(game) is "object"
    
    game.score = 100;//null is not an object, what the heck!?
    game instanceof Object; //false, so it's not an instance but it's type is object
    //let's make this primitive variable an object;
    game = {}; 
    typeof(game);//it is an object
    game instanceof Object; //true, yay!!!
    game.score = 100;
    

    Undefined case:

    var score; //at this point 'score' is undefined
    typeof(score); //'undefined'
    var score.player = "felix"; //'undefined' is not an object
    score instanceof Object; //false, oh I already knew that.
    

提交回复
热议问题