JavaScript method of object not working -
i'm trying create simple object method changes value of 1 of keys. want initialize isfoodwarm key false, output value, change true, output again. expected output false , true, method should change true, getting error. tried removing parentheses mybreakfast.heat();, got rid of error, didn't change value. doing wrong? here code.
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 warm"); } } } var mybreakfast = new breakfast("english muffin", "oj", "false"); console.log(mybreakfast.isfoodwarm); mybreakfast.heat(); console.log(mybreakfast.isfoodwarm); i following console output:
false
uncaught typeerror: mybreakfast.heat not function
you need attach heat method constructor breakfast too. , isfoodwarm property must accessed using this.isfoodwarm inside heat method.
this.heat=function() { if (this.isfoodwarm === false){ this.isfoodwarm = true; console.log("your food warm"); } } explanation : without this operator heat method gets attached global object, when call mybreakfast.heat gives uncaught typeerror because defined under window.heat.
note : when need pass boolean don't wrap inside quotes change boolean string behave true.
so change constructor call
new breakfast("english muffin", "oj", false); \\remove double quotes around false demo
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 warm"); } } } var mybreakfast = new breakfast("english muffin", "oj", false); console.log(mybreakfast.isfoodwarm); mybreakfast.heat(); console.log(mybreakfast.isfoodwarm);
Comments
Post a Comment