Javascript .call 函数返回额外的 'undefined' 值

Javascript .call function returning extra 'undefined' value

在以下代码段中:

function Product(name, price) {
  this.name = name;
  this.price = price;
  this.show = function() {
      console.log(this.name);
      console.log(this.price * 10);
      };
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

console.log(fun.show());

我得到的控制台输出是:

robot
400
undefined

为什么第三个输出是 undefined,它来自哪里?

默认情况下,JS 函数 return 未定义。

由于您的 show 函数未明确 returning 任何内容,因此它 return 未定义。

使用 return 而不是多次登录到控制台。

function Product(name, price) {
  this.name = name;
  this.price = price;
  this.show = function() {
      return this.name + " " + String(this.price * 10)
  };
}

function Food(name, price) {
  Product.call(this, name, price);
  this.category = 'food';
}

function Toy(name, price) {
  Product.call(this, name, price);
  this.category = 'toy';
}

var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);

console.log(fun.show());

出品:robot 400(玩具名称及价格)