在以下代码段中:
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
,它是从哪里来的?
答案 0 :(得分:3)
默认情况下,JS函数返回未定义。
由于您的show
函数未明确返回任何内容,因此它返回的是未定义的。
答案 1 :(得分:1)
使用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
(玩具名称和价格)