簡單說一下call方法調(diào)用父類構(gòu)造函數(shù)衣撬。
在一個子構(gòu)造函數(shù)中撰糠,你可以通過調(diào)用父構(gòu)造函數(shù)的call方法來實現(xiàn)繼承饥悴,類似于Java中的寫法蒿秦。下例中烤镐,使用 Food 和 Toy 構(gòu)造函數(shù)創(chuàng)建的對象實例都會擁有在 Product 構(gòu)造函數(shù)中添加的 name 屬性和 price 屬性,但 category 屬性是在各自的構(gòu)造函數(shù)中定義的。
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); //穿進去三個參數(shù)棍鳖,第一個this函數(shù)作為隱式參數(shù)傳入
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
Food.prototype.constructor = Food; // Reset the constructor from Product to Food
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = Object.create(Product.prototype);
Toy.prototype.constructor = Toy; // Reset the constructor from Product to Toy
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);