Chrome 仅使用以下代码记录 undefined
:
<!DOCTYPE html><html lang="en"><body><script>
var cody = new Object();
console.log(cody.prototype);
</script></body></html>
而且我认为它应该是Object.prototype
,但现在是undefined
,为什么?
我尝试了 for (var p in cody){console.log(p);}
但什么也没得到。
最佳答案
它是具有 prototype
属性的构造函数(在本例中为Object
)。一个实际的实例 获取对 the __proto__
property 中原型(prototype)的引用:
var cody = new Object();
console.log(cody.__proto__ === Object.prototype);
// => true
请注意,这是未标准化。来自 MDN 文档:
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
在现代浏览器中,您也可以应该使用Object.getPrototypeOf
:
console.log(Object.getPrototypeOf(cody) === Object.prototype);
// => true
关于javascript - 为什么由 new Object() 创建的对象的原型(prototype)未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334371/