为什么null在JavaScript中被认为是一个对象?

正在检查

if ( object == null )
      Do something

if ( !object )
      Do something

?

还有:

null和undefined之间的区别是什么?


当前回答

摘自Nicholas C. Zakas的《面向对象的Javascript原理》

但是为什么对象类型是空的呢?(事实上,TC39(设计和维护JavaScript的委员会)已经承认这是一个错误。你可以推断null是一个空对象指针,使“object”成为一个逻辑返回值,但这仍然令人困惑。)

尼古拉斯·扎卡斯(2014-02-07)。面向对象JavaScript的原则(Kindle位置226-227)。没有淀粉机。Kindle版。

也就是说:

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;

未定义的例子:

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.

其他回答

摘自Nicholas C. Zakas的《面向对象的Javascript原理》

但是为什么对象类型是空的呢?(事实上,TC39(设计和维护JavaScript的委员会)已经承认这是一个错误。你可以推断null是一个空对象指针,使“object”成为一个逻辑返回值,但这仍然令人困惑。)

尼古拉斯·扎卡斯(2014-02-07)。面向对象JavaScript的原则(Kindle位置226-227)。没有淀粉机。Kindle版。

也就是说:

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;

未定义的例子:

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.
typeof null;      // object
typeof undefined; // undefined

null值表示有意不存在任何对象值。它是JavaScript的基本值之一,在布尔操作中被视为假值。

var x = null;
var y;

X被声明并定义为null

Y声明了,但没有定义。它声明时没有值,所以没有定义。

Z没有被声明,所以如果你试图使用Z,它也是未定义的。

在Javascript中,null不是对象类型,而是原始类型。

有什么不同? Undefined指的是一个没有被设置的指针。 Null指的是空指针,例如有人手动将一个变量设置为Null类型

例如窗口。someWeirdProperty是未定义的

”窗口。someWeirdProperty === null"的值为false时

”窗口。someWeirdProperty === undefined"的值为true。

此外,checkif if (!o)与检查if (o == null)是否为假并不相同。

null和undefined的主要区别在于null表示 一个缺失的对象,而undefined表示变量的未初始化状态。

你可以认为null是一个未定义的对象,但未定义只是未定义的 因为它的类型没有定义。

let a; 
console.log(a); //undefined, since it is declared but not initialized

console.log(null == undefined) //true
console.log(null === undefined) // false

console.log(typeof null) //object
console.log(typeof undefined) //undefined