为什么代码放在return语句之后,它会被执行吗?

时间:2014-05-27 09:36:06

标签: javascript constructor call

我不明白为什么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);

1 个答案:

答案 0 :(得分:1)

  

据我所知,如果函数返回代码,之后将无法执行。

  

我在这里错过了什么吗?

return在本地工作,只结束当前的函数调用。在设置Food属性之前,return函数不会.category

顺便说一下,return中的Product是不必要的,因为构造函数不需要显式返回。