简体   繁体   English

为什么布尔值未定义?

[英]Why is the boolean undefined?

In javascript I do: 在javascript中,我这样做:

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? 从myMethod的角度来看,为什么myBoo无法确定?

Thanks. 谢谢。

This is because myBoo is not defined as a global variable, but rather as an object property. 这是因为myBoo没有定义为全局变量,而是定义为对象属性。 The proper way of accessing it in the myMethod function would therefore be: 因此,在myMethod函数中访问它的正确方法是:

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/ 这是一个小提琴: http : //jsfiddle.net/9xB83/

Here's a great article about this http://www.quirksmode.org/js/this.html . 这是有关 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. myBoo是对象的属性,因此您必须参考对象本身来访问它。

it should be this.myBoo in the myMethod function() 它应该是myMethod函数中的this.myBoo()

Your function "myMethod" is trying to access local variable myBoo which doesn't exist in the context of your function! 您的函数“ myMethod”正在尝试访问在函数上下文中不存在的局部变量myBoo! What you meant to do is use this.myBoo. 您的意思是使用this.myBoo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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