【问题标题】:Why is it necessary to use Object.create()为什么需要使用 Object.create()
【发布时间】:2014-10-01 01:35:44
【问题描述】:

这是我的代码:

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)继承是必要的,如果是,为什么?

【问题讨论】:

标签: javascript oop object inheritance prototype


【解决方案1】:

这一行

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

会报错TypeError: Object # has no method 'calculateTax'

【讨论】:

  • 谢谢Khnle,这个答案非常简洁。
猜你喜欢
  • 2014-02-17
  • 2013-02-24
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-09
相关资源
最近更新 更多