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

Why the code is put after the return statement, will it get executed?

本文关键字:执行 之后 代码 return 语句 为什么      更新时间:2023-09-26

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

据我所知,如果函数返回之后的代码将不会被执行。

是的。

我错过了什么吗?

return在本地工作,只结束当前函数调用。

设置.category属性前,Food功能不设置return

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