【问题标题】:How does JavaScript maintain the prototype reference?JavaScript 如何维护原型引用?
【发布时间】:2015-10-20 23:06:54
【问题描述】:

查看 (How does the prototype chain work?) 的答案,我可以看到有一个继承链。幕后发生了什么?

据我所知,原型属性存储了对原型对象的引用?为什么该对象不包含原型的原型,以及它是如何维护该引用的?

var Parent = function() {
	this.name = 'Parent';
}

Parent.prototype.sayHi = function() {
	console.log('hi');
}

var Child = function() {
	this.name = "Child";
}

Child.prototype = new Parent();

console.log(Parent.prototype); // { sayHi: [Function] }
console.log(Child.prototype); // { name: 'Parent' }
console.log(Child.prototype.prototype); // undefined

=============== 下面回答===============

console.log(Parent.prototype); // { sayHi: [Function] }
console.log(Child.prototype); // { name: 'Parent' }
console.log(Child.prototype.__proto__); // { sayHi: [Function] }

【问题讨论】:

  • 这不是您代码的正确输出。创建一个内联 sn-p。
  • 它确实“包括原型的原型”,如果你设置了这样的关系。在显示的代码中,没有将 Child 绑定到 Parent,因此如果它们为您连接,那将是令人惊讶的......
  • 抱歉,现在可以了。但我仍然得到相同的输出

标签: javascript inheritance prototype prototypal-inheritance


【解决方案1】:

为什么该对象不包含原型的原型,它是如何维护该引用的?

因为在您的示例中,Childprototype 也是Parent 的一个实例,而不是另一个构造函数。 prototype 是构造函数的属性,而不是每个实例的属性。

还有另一个属性为每个实例执行此操作,__proto__ 属性,但它几乎没有合理的用途。 ES6 规范也只要求该功能在 Web 浏览器中实现,而不一定要在其他 JavaScript 环境中实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2015-02-05
    相关资源
    最近更新 更多