0

为什么:

console.log(Object.hasOwnProperty("hasOwnProperty"));   

返回一个错误,但是:

console.log(Object.prototype.hasOwnProperty("hasOwnProperty"));  

返回一个真实的陈述?

我意识到 hasOwnProperty 是 Object 中的预构建方法,但我想我的问题是 Object 和 Object 的原型之间有什么区别。
他们不是一回事吗?
当我们在第一行代码中引用 Object 时,我们不是在上面第二行代码中引用同一行代码吗?

编辑:固定以上两行代码:

console.log(Object.hasOwnProperty);

和:

console.log(Object.prototype.hasOwnProperty);  
4

2 回答 2

1

两者都Object.hasOwnProperty引用Object.prototype.hasOwnProperty相同的函数Object.prototype包含该函数作为自己的属性,而Object包含它作为继承的属性。

因此,换句话说,函数是在对象hasOwnProperty上定义的(作为方法) 。Object.prototype然后,Object构造函数(与几乎所有其他本地对象一样)从Object.prototype.

顺便说一句,继承链(原型链)Object是:

Object -> Function.prototype -> Object.prototype -> null

因此,Object继承了Function.prototype, 和的所有方法Object.prototype

于 2013-02-11T17:53:03.160 回答
0

我意识到 hasOwnProperty 是 Object 中的预构建方法。

实际上,它是所有JavaScript 对象都继承自该对象的不可枚举属性的函数。这包括Object函数对象。

但我想我的问题是对象和对象的原型有什么区别。他们不是一回事吗?

No, they're definitely not. The section on Objects in the Language Overview of the EcmaScript specification describes it pretty well I think. Each object has a hidden [[prototype]] link to the object it inherits from (until null) - building the "prototype chain" in which properties are looked up. The public prototype property of functions is different from that - it points to the object from which all instances that are constructed by the function will inherit.

于 2013-02-11T17:55:07.080 回答