我不明白为什么Function.prototype.call()可以这样使用?据我所知,如果函数返回代码后不会执行。我错过了什么吗?
function Product(name, price) {
this.name = name;
this.price = price;
if (price < 0)
throw RangeError('Cannot create product
"' + name + '" with a negative price');
return this;
}
function Food(name, price) {
Product.call(this, name, price); // if the function returns here why put this.category after this statement?
this.category = 'food'; // will this ever get executed?
}
Food.prototype = Object.create(Product.prototype);
var cheese = new Food('feta', 5);
据我所知,Product,Food都是构造函数,我们可以使用对象的链构造函数的调用,类似于Java。但为什么不发表声明
this.category = 'food';
之前
Product.call(this, name, price);
答案 0 :(得分:1)
据我所知,如果函数返回代码,之后将无法执行。
是
我在这里错过了什么吗?
return
在本地工作,只结束当前的函数调用。在设置Food
属性之前,return
函数不会.category
。
顺便说一下,return
中的Product
是不必要的,因为构造函数不需要显式返回。