[英]Why is it necessary to use Object.create()
這是我的代碼:
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0) throw RangeError('Invalid');
return this;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = Object.create(Product.prototype);
var cheese = new Food('feta', 5);
當我在控制台中檢查變量時,我看到以下內容:
Food {name: "feta", price: 5, category: "food"}
這是我的預期。
但是,如果我省略Object.create(Product.prototype)
我會看到相同的結果,因為Product.call
。
Object.create(Product.prototype)
甚至是繼承所必需的,如果是,為什么呢?
這條線
Product.call(this, name, price);
給出與...相同的效果
this.name = name; //argument name from the function constructor
this.price = price; //likewise, argument of function constructor
但它沒有設置Food對象的prototype屬性。 有了這條線
Food.prototype = Object.create(Product.prototype);
它確保如果查找Food對象的屬性並且JavaScript找不到它,它將遵循原型鏈到Product.prototype
讓我們詳細說明你的例子
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0) throw RangeError('Invalid');
return this;
}
並添加一個計算稅收的功能
Product.prototype.calculateTax = function() {
return this.price * 0.1;
}
現在用這條線
Food.prototype = Object.create(Product.prototype);
以下將正確計算稅額
var cheese = new Food('feta', 5);
console.log(cheese.calculateTax());
省略那條線
//Food.prototype = Object.create(Product.prototype);
它會給出錯誤TypeError:Object#沒有方法'calculateTax'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.