Possible Duplicate:
“this” inside object
我正在尝试为我正在开发的 jQuery 插件的几个默认选项创建一个对象文字:
var defaults = {
r: 5,
top: this.r,
bottom: this.r,
topleft: this.top,
topright: this.top,
bottomleft: this.bottom,
bottomright: this.bottom
};
当我引用defaults.top
时它是undefined
我能做些什么来完成这项工作吗?或者也许有不同的方法?我需要它是一个对象文字。
添加:
它是(default
对象),正如你所看到的,它的层叠方式是一种速记技术。例如,如果您想将所有 Angular 定义为相同,则可以使用 {r: 5}
但如果你想让顶部和底部不同{top: 5, bottom: 1}
再次,单独{topleft: 5, topright:2, bottomleft: 3, bottomright:19 }
对于没有说清楚这一点,我深表歉意,但非常感谢您的回答。
回答:这就是我最终所做的
if(o.topleft == undefined || o.topright == undefined || o.bottomleft == undefined || o.bottomright == undefined){
if(o.top == undefined || o.bottom == undefined){
if(o.r == undefined){
o.topleft = 5;
o.topright = 5;
o.bottomleft = 5;
o.bottomright = 5;
}else{
o.topleft = o.r;
o.topright = o.r;
o.bottomleft = o.r;
o.bottomright = o.r;
}
}
else{
o.topleft = o.top;
o.topright = o.top;
o.bottomleft = o.bottom;
o.bottomright = o.bottom;
}
}
晚餐马虎,但是嘿,它成功了!谢谢你的帮助!我选择这个答案是因为这个解释引导我这样做!
最佳答案
"when I reference the
defaults.top
it isundefined
"
这是因为 this
并不引用您正在创建的对象,它是来自代码运行的任何范围的 this
。
对象字面量语法不允许您通过引用同一对象中的其他属性来设置值 - 该对象尚不存在。您可以引用在对象字面量之前声明的其他变量或函数。因此,如果您需要所有属性与示例中的相同,那么您可以这样做:
var val = 5,
defaults = {
r: val,
top: val,
bottom: val,
topleft: val,
topright: val,
bottomleft: val,
bottomright: val
};
或者使用对象文字创建一些属性,然后设置其余属性:
var defaults = {
r : 5
};
defaults.top = defaults.bottom = defaults.r;
defaults.topleft = defaults.topright = defaults.top;
// etc
显然,后者更适合将某些属性设置为一个值,将其他属性设置为另一个值。 (尽管在您的示例中所有属性都是相同的。)
无论哪种方式最终都会给你相同的对象(对象文字只是创建对象的快捷方式)。
" I would like it to be simple enough to do something like this
$(selector).myPlugin({r:10});
or$(selector).myPlugin({top:10, bottom: 5});
"
好吧,您仍然可以使用对象文字作为参数调用插件。但是 defaults
对象(我假设是在插件内部定义的)可以使用其他技术来定义。
关于Javascript对象字面量,如何使用 'this'引用对象中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11920448/