[英]Accessing an object inside another object
Hi I am getting an uncaught reference exception on my code.This is what I have: 嗨,我在代码中遇到了一个未捕获的引用异常,这是我所拥有的:
var config = {
debug: true,
data: {
debug: false,
logErrorsOnServer: true,
defaultCulture: '',
serviceUrl: ''
},
init: function(options) {
if (!options) {
return;
}
if (options.hasOwnProperty('debug')) {
data.debug = options.debug;
}
},
};
When I try to get the value of data.debug I get an uncaught reference error that says: 当我尝试获取data.debug的值时,出现未捕获的引用错误,内容为:
UncoughtReference Error: data is not defined
Whay can't I acces my data object? 我无法访问我的数据对象吗?
You need to say: 您需要说:
this.data.debug = options.debug;
...assuming that you are calling the init()
function in a way that sets this
to the (outer) object, eg, with config.init()
. ......假设你正在调用
init()
中,设置一个单向函数this
给(外)的对象,例如,用config.init()
Or you can say: 或者你可以说:
config.data.debug = options.debug;
The reason you got an error about data
not being defined when you tried to use data.debug
directly is that in fact data
is not defined as a variable, it is a property of the object. 你有关于一个错误的原因
data
,当您尝试使用没有被定义data.debug
直接的是,实际上data
没有被定义为一个变量,它是对象的属性。 Just because init()
is a method on your object doesn't mean it automatically references other object properties. 仅仅因为
init()
是对象上的一种方法,并不意味着它会自动引用其他对象属性。
Well, the data
variable is undefined. 好吧,
data
变量 是不确定的。 You probably want to use the object on your .data
property of config
(accessible via the this
keyword ): 您可能想在
config
的.data
属性上使用该对象(可通过this
关键字访问):
…
if (options.hasOwnProperty('debug')) {
this.data.debug = options.debug;
}
…
See also Javascript: Object Literal reference in own key's function instead of 'this' for different methods to access .data
. 另请参见Javascript:自己键函数中的Object Literal引用(而非“ this”) ,以获取用于访问
.data
不同方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.