我正在尝试使用更改其中一个键的值的方法创建一个简单的对象。我想将 isFoodWarm 键初始化为 false,输出该值,将其更改为 true,然后再次输出。我的预期输出是 false,然后是 true,因为该方法应该将其更改为 true,但我收到错误。我尝试从 myBreakfast.heat(); 中删除括号,这消除了错误,但随后它没有成功更改值。我究竟做错了什么?这是我的代码。
function Breakfast(food, drink, isFoodWarm) {
this.food = food,
this.drink = drink,
this.isFoodWarm = isFoodWarm,
heat = function() {
if (isFoodWarm === false){
isFoodWarm = true;
console.log("your food is now warm");
}
}
}
var myBreakfast = new Breakfast("english muffin", "OJ", "false");
console.log(myBreakfast.isFoodWarm);
myBreakfast.heat();
console.log(myBreakfast.isFoodWarm);
我得到以下控制台输出:
假
未捕获的类型错误:myBreakfast.heat 不是函数
最佳答案
您还需要将 heat 方法附加到构造函数BreakFast
。而且 isFoodWarm
也是一个属性,因此必须在 heat
方法中使用 this.isFoodWarm
来访问它。
this.heat=function() {
if (this.isFoodWarm === false){
this.isFoodWarm = true;
console.log("your food is now warm");
}
}
解释:如果没有 this
运算符 heat 方法会附加到全局对象,因此当您调用 myBreakfast.heat
时,它会给出 Uncaught TypeError
因为它在 window.heat
下定义。
注意:当您需要传递 bool 值时,不要将其括在引号内,因为它会将您的 bool 值更改为字符串,其行为类似于 true。
因此将构造函数调用更改为
new Breakfast("english muffin", "OJ", false); \\remove double quotes around false
演示
function Breakfast(food, drink, isFoodWarm) {
this.food = food,
this.drink = drink,
this.isFoodWarm = isFoodWarm,
this.heat = function() {
if (this.isFoodWarm === false){
this.isFoodWarm = true;
console.log("your food is now warm");
}
}
}
var myBreakfast = new Breakfast("english muffin", "OJ", false);
console.log(myBreakfast.isFoodWarm);
myBreakfast.heat();
console.log(myBreakfast.isFoodWarm);
关于对象的 JavaScript 方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30762663/