javascript - 继承和原型(prototype)链

标签 javascript inheritance prototype

我最近一直在通过 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/

相关文章:

javascript - 如何使用 JS 从 MySQL 时间戳中获取月份

javascript - 如何在最初由ajax加载时将表单作为GET方法提交

javascript - (window).load 预加载站点并提供中止选项

javascript - 在 Javascript 中创建子类时,为什么要分配原型(prototype)字段?

javascript - 如果值太高,本地存储将停止工作

c++ - Qt:子类中无法识别继承的信号

.net - 如何覆盖不可继承类中的属性?

java - Field#getAnnotations() 和 Field#getDeclaredAnnotations() 之间的区别

javascript - 从子对象修改原型(prototype)上的字段

javascript - 处理类内的事件(原型(prototype))