简体   繁体   中英

Why is the boolean undefined?

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.

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.net/9xB83/

Here's a great article about this http://www.quirksmode.org/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM