我最近一直在通过 Mozilla 开发者网络阅读有关 JavaScript 继承模型的内容。有一点我很困惑。这是来自 MDN 的代码:
function Graph() {
this.vertices = [];
this.edges = [];
}
Graph.prototype = {
addVertex: function(v) {
this.vertices.push(v);
}
};
var g = new Graph();
console.log(g.hasOwnProperty('vertices'));// true
console.log(g.hasOwnProperty('addVertex'));// false
console.log(g.__proto__.hasOwnProperty('addVertex'));// true
我不明白的是,为什么 g.hasOwnProperty('addVertex')
会产生 false,因为 addVertex 是 g 的一个属性,尽管它是在 Graph 的原型(prototype)中定义的,但它仍然是 Graph 的一部分.
我还有一个问题:如果某个对象继承自 g(或者说 Graph),它会只继承 addVertex(在函数原型(prototype)中定义的那些)还是会继承图的所有三个属性,即顶点、边和添加顶点。
最佳答案
why does g.hasOwnProperty('addVertex') yields false
这就是 hasOwnProperty
的工作方式。来自 MDN :
The
hasOwnProperty()
method returns a boolean indicating whether the object has the specified property as own (not inherited) property.
因此 hasOwnProperty
在进行检查时不会遍历原型(prototype)链。
您可以使用 in运算符检查原型(prototype)链中的属性。
关于javascript - 继承和原型(prototype)链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45659284/