为什么DOMWindow类型是null和undefined ?
Why are null and undefined of the type DOMWindow?
当您在浏览器或Node.js中运行以下代码时,您将得到注释中列出的预期结果:
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
当你在PhantomJS中运行这段代码时,然而,在这两种情况下,输出都是[object DOMWindow]
。
这看起来很奇怪,因为undefined
和null
都是本机类型。typeof
操作符看起来像在其他环境中一样工作(包括typeof null === "object"
怪癖),所以看起来PhantomJS至少有未定义类型的概念:
typeof undefined; // "undefined"
它还声称Object.prototype.toString
包含本机代码,这可能表明Phantom本身没有做任何事情来修改实现(我不知道情况是否如此-尽管我无法在源代码中找到任何有用的东西):
Object.prototype.toString.toString(); // "function toString() { [native code] }"
那么为什么PhantomJS不使用(或至少暴露)正确的[[Class]]
属性值为null
和undefined
,我有办法改变吗?我知道我可以使用不同的方法来确定类型,但我宁愿不这样做。
这是两件事的结合。脚本在web页面中执行,因此全局对象是window
对象,如:
console.log(this.toString()); // [object DOMWindow]
此外,该版本的JavaScript实现存在一个问题,即在上述条件下伪造对象原型链。
这可能会在将来的某个版本中修复。
我承认我有点言过其实了,但是MDN关于Object.toString()
的文章提到:
从JavaScript 1.8.5开始,toString()调用null返回[object null], undefined返回[object undefined],如ECMAScript第5版和随后的勘误表中定义的那样。参见使用toString检测对象类型。
链接的部分然后描述您正在使用的构造Object.prototype.toString(null)
。因此,似乎能够合理地将null
和undefined
字符串化是对Javascript的一个新的(-ish)添加/修正,而PhantomJS引擎(苹果的JavaScriptCore,谁知道是哪个版本)还没有实现。也就是说,这在Safari 6中可以正常工作,所以可能值得将其作为错误报告,要求符合ES5。
如果只有这两种类型,我想你可以用这个来围绕你的问题。
Object.prototype.toString = function(obj){
if(typeof(obj) == "undefined"){
return "[object Undefined]";
}
if(typeof(obj) == "null"){
return "[object Null]";
}
return obj.toString();
}
- getElementById 在 Safari 中返回 null 或 undefined
- 为什么是 isFinite(undefined) != isFinite(null)
- 为什么"undefined为null或不是对象”;
- results[0].formatted_address return undefined or null
- javascript中undefined和null的区别是什么,它们的用例是什么
- Angularjs变量undefined、null和empty同时出现
- Undefined vs null in javascript
- 为什么javascript ' var undefined '是OK的,但' var null '抛出错误
- JavaScript Regex匹配返回null或undefined
- Are [object Null] &[object Undefined]有待实现
- 反应.createElement: type不应该是null、undefined、boolean或number.它应该是
- 迭代react元素中的undefined/null对象
- 警告:反应.createElement: type不应该是null、undefined、boolean或number
- 解释如果Type(x)是Undefined,返回true.如果Type(x)为Null,则返回true
- 为什么 null==undefined 在 JavaScript 中是正确的
- ES6 ReactJS: React.createElement: type不应该是null、undefined、boo
- 是否可以使用变量!= null而不是变量!== undefined &&== null
- 如何从"null"筛选嵌套数组和“;undefined"值
- Javascript不能访问document: null或undefined
- 可以在检查undefined/null时使用类型强制转换