为什么有必要使用 Object.create()

Why is it necessary to use Object.create()

本文关键字:Object create 为什么      更新时间:2023-09-26

这是我的代码:

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 对象的原型属性没有任何作用。 用这条线

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);

它将给出错误类型错误:对象 # 没有方法"计算税">