最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is the boolean undefined? - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 3

This 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.

发布评论

评论列表(0)

  1. 暂无评论