【发布时间】:2015-07-02 03:33:31
【问题描述】:
我正在查看来自MDN 的关于继承和原型的两个示例。鉴于这两个例子,我的理解似乎有些冲突——它们似乎是矛盾的:
var a = {a: 1};
//inheritance looks like: a ---> Object.prototype ---> null
var b = Object.create(a);
//inheritance looks like: b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)
到目前为止是有道理的,但是在另一个页面上,学习了 .call() 方法:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0) {
throw RangeError('Cannot create product ' +
this.name + ' with a negative price');
}
return this;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = Object.create(Product.prototype);
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
Food 的原型现在不就是 Product 的原型了吗?即 Function.prototype?
我期待:
Food.prototype = Object.create(Product)
这是否与它是一个函数这一事实有关?
谢谢,
【问题讨论】:
-
"i.e Function.prototype?"
prototype的属性function最初是一个普通的Object。该属性用于继承而不是function本身,因此各种类型不必继承Function行为。 -
Constructor.prototype是对应该由Constructor的实例继承的对象的引用,而obj.prototype只是一个常规属性,就像任何其他属性一样,例如a.prototype和@987654334 @ 在你的代码中都是 undefined.
标签: javascript inheritance prototype