如何在不使用javascript函数的情况下使用对象文字的属性 [英] How to use properties of an object literal without being inside a function in javascript
问题描述
我在JS中创建了一个对象文字,但是想要在不使用函数的情况下访问属性。每当我尝试时,我都没有得到任何结果,或者它返回 null
。
I created an object literal in JS, but wanna to access a property without being in a function. Whenever I try, I don't get any results or it returns null
.
JS:
var settings = {
prev: '#prev',
next: '#next',
slides: '#slides',
crslContainer: '#carousel',
//I'm trying to access the 'slides' by using 'this.slides'
inDent: $(this.slides).find('li').outerWidth(),
fx: 'rotate',
myFunction: function () {
console.log(settings.inDent); //This shows null in the console, why??
}
}
在上面的代码中我试图访问幻灯片
使用 this.slides
,都在同一个对象中,但控制台说 null
。但是当我使用方法时, inDent:$('#slides')。find('li')。outerWidth()
,然后它就可以了。这是为什么?我假设它与使用这个
关键字在函数内使用这些属性相同,显然情况并非如此。
我只是想将该对象属性的值(即字符串)传递给另一个不是函数的属性。
In the code above I'm trying to access slides
by using this.slides
, all inside the same object, but the console says null
. But when I do the method, inDent: $('#slides').find('li').outerWidth()
, then it works. Why is that? I assumed it's the same as using those properties inside a function by using this
keyword, apparently it's not the case.
I just wanna pass the value of that object property , i.e. a string, to another property that's not a function.
非常感谢
推荐答案
您不能在对象文字中引用正在定义的对象。也就是说,没有办法让under-construction对象的属性的值表达式引用对象本身,以便访问另一个(可能是已经定义的)属性。
You can't refer to the "object being defined" in an object literal. That is, there's no way to have the value expression for a property of the under-construction object refer to the object itself in order to access another (presumably, already-defined) property.
然而,您可以在定义对象后添加属性。
You can however add a property to the object after it's been defined.
var obj = { a: 0 };
obj.b = (obj.a ? 1 : 2);
或者在您的情况下:
var settings = { ... };
settings.inDent = ($(settings.slides).find('li').outerWidth());
这篇关于如何在不使用javascript函数的情况下使用对象文字的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!