为什么有必要使用 Object.create()
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 对象的原型属性没有任何作用。 用这条线
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);
它将给出错误类型错误:对象 # 没有方法"计算税">
相关文章:
- 使用Object.create()的角度服务继承
- 在使用object.create创建的对象中使用super
- 正在使用object.create()创建XMLHttpRequest对象
- Object.create()只读名称属性
- childObj.prototype = Object.create(parentObj.prototype) 和 ch
- object.create 不使用我的新值
- Object.create() instead of prototype
- Object.create and Prototypes
- Javascript Object.create
- 使用Object.create作为原型的原型继承将[Object]作为实例的原型
- 不涉及私有“函数”的“Object.create”的自定义实现
- 正在对通过object.create创建的对象设置原型
- javascript中的Object.create方法
- 重写JavaScript中的Object.create方法
- 在不使用object.Create的情况下创建具有null原型的javascript对象
- JavaScript inheritance Object.create
- 为什么MDN Object.create polyfill上的Temp.prototype设置为null
- 使用Object.create()创建对象的模式
- 使用“new”关键字创建的对象和使用“Object.create”创建的对象给出不同的结果
- Object.create Prototype Chains