我目前正在研究 javascript 的 Object.prototype.toString
方法。
在 MDN reference page on Object.prototype.toString ,它提到了
Note: Starting in JavaScript 1.8.5 toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and a subsequent Errata.
所以
var a = undefined;
Object.prototype.toString.call(a); //chrome prints [object Undefined]
var b = null;
Object.prototype.toString.call(b); //chrome prints [object Null]
但我认为 null
和 undefined
都是原始类型,没有相应的包装类型(不像 string
原始类型和 String
对象包装器),那么为什么实际上 null 和 undefined 不是对象时却打印了 [object Null]
和 [object Undefined]
。
而且,我认为使用像 Object.prototype.toString.call(a)
这样的代码,它与 a.toString()
相同(即使用 a
作为 toString()
函数中的 this
),但是当我尝试
var a = undefined;
a.toString();
Chrome 打印错误消息
Uncaught TypeError: Cannot read property 'toString' of undefined
我的想法是,undefined
不以任何方式原型(prototype)链接到 Object.prototype
,这就是 a.toString()
失败的原因,但是Object.prototype.toString.call(a)
怎么会成功呢?
最佳答案
未定义就是未定义。 Null被视为一个对象,但不继承全局对象的任何方法。
您可以对它们两者调用 Object.prototype.toString.call 而不是 undefined.toString 或 null.toString 的原因是第一个是简单的函数调用。第二个是尝试调用一个对象方法,但两者都没有。根据 Mozilla 的说法,typeof null “出于遗留原因”返回对象。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null
var a;
console.log(typeof a);
console.log(Object.prototype.toString.call(a)); //chrome prints [object Undefined]
console.log(typeof Object.prototype.toString.call(a));
var b = null;
console.log(typeof b);
console.log(Object.prototype.toString.call(b)); //chrome prints [object Null]
console.log(typeof Object.prototype.toString.call(b));
关于javascript - 使用未定义和 null 的 Object.prototype.toString 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45227202/