In javascript I do:
var myObject = {
myBoo: false,
myMethod: function () {
console.log("my method: "+ myBoo);
}
}
console.log("myObject.myBoo=" + myObject.myBoo);
myObject.myMethod();
This outputs:
myObject.myBoo=false
ReferenceError: myBoo is not defined
Why is myBoo undefeind from myMethod's perspective?
Thanks.
In javascript I do:
var myObject = {
myBoo: false,
myMethod: function () {
console.log("my method: "+ myBoo);
}
}
console.log("myObject.myBoo=" + myObject.myBoo);
myObject.myMethod();
This outputs:
myObject.myBoo=false
ReferenceError: myBoo is not defined
Why is myBoo undefeind from myMethod's perspective?
Thanks.
Share Improve this question asked Apr 17, 2012 at 10:59 dublintechdublintech 17.8k31 gold badges88 silver badges118 bronze badges4 Answers
Reset to default 3This is because myBoo is not defined as a global variable, but rather as an object property. The proper way of accessing it in the myMethod
function would therefore be:
console.log("my method: "+ this.myBoo);
You need to add this to refer to the object:
myMethod: function () {
console.log("my method: "+ this.myBoo);
}
Here's a fiddle: http://jsfiddle/9xB83/
Here's a great article about this http://www.quirksmode/js/this.html.
myBoo is an attribute of the object hence you will have to access it in reference to the object itself.
it should be this.myBoo in the myMethod function()
Your function "myMethod" is trying to access local variable myBoo which doesn't exist in the context of your function! What you meant to do is use this.myBoo.