Javascript 调用函数返回额外的';未定义';价值

Javascript 调用函数返回额外的';未定义';价值,javascript,call,Javascript,Call,在以下代码段中: 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)

在以下代码段中:

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

为什么第三个输出是未定义的?

默认情况下,JS函数返回未定义的


由于
show
函数没有显式返回任何内容,因此它返回未定义的内容。

使用
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
(玩具名称和价格)

show
不返回任何东西,但您正在记录返回。您希望它返回什么以及为什么?我想补充一点,OP可能要替换:
console.log(fun.show())使用:
fun.show()因为1)
show()
已经在调用
console.log
和2)
show()
没有返回任何内容(这意味着它实际上会按照您的建议返回
未定义的