对象的 JavaScript 方法不起作用

标签 javascript object

我正在尝试使用更改其中一个键的值的方法创建一个简单的对象。我想将 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/

相关文章:

javascript - HTML5 Canvas 访问控制允许来源错误

javaScript 淡入 OnLoad

javascript - 在原型(prototype)中使用 css 选择器触发点击事件

具有 2 个或更多对象的页面上的 javascript 设计模式

Java/Android 使用一个 obj 指针来引用 2 个类

java - 我应该如何将 json 值返回到另一个方法中

java - 递增和递减变化的对象值

javascript - 如何在我们写的时候自动扩展文本区域

java - 在另一个类中使用内部类actionListener

javascript - 未捕获的安全错误 : Failed to execute 'getImageData' on 'CanvasRenderingContext2D' :