admin管理员组文章数量:1400110
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.
本文标签: javascriptWhy is the boolean undefinedStack Overflow
版权声明:本文标题:javascript - Why is the boolean undefined? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744197106a2594792.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论