最近,我一直在阅读关于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')会产生假,因为addVertex是g的一个属性,虽然它是图的原型中定义的,但它仍然是图的一部分。
另外,我还有一个问题:如果某个对象继承了g(或者这么说是图),它将只继承addVertex (函数原型中定义的对象),或者它将继承图的所有三个属性,即顶点、边和addVertex。
发布于 2017-08-13 10:32:53
因为hasOwnProperty明确表示它在inherited属性上返回false
hasOwnProperty()方法返回一个布尔值,指示对象是否将指定的属性作为自己的(而不是继承的)属性。
至于第二个问题,这完全取决于,是如何从Graph继承对象的。以ES5的方式,我会这样做:
var InheritedFromGraph = function() {
Graph.call(this);
}
InheritedFromGraph.prototype = Graph.prototype;然后,是的,InheritedGraph将得到Graph在其构造函数中定义的属性verticies和edge。
https://stackoverflow.com/questions/45659284
复制相似问题