JavaScript如何维护原型参考?

时间:2015-07-29 19:26:12

标签: javascript inheritance prototype prototypal-inheritance

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

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

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] }

1 个答案:

答案 0 :(得分:3)

  

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

因为在您的示例中,prototype的{​​{1}}也是Child的实例,而不是其他构造函数。 Parent是构造函数的属性,而不是每个实例的属性。

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