Javascript对象文字,如何使用“this”来引用对象中的变量

Javascript object literal, how to use 'this' to reference a variable in the object

本文关键字:对象 引用 变量 文字 何使用 Javascript this      更新时间:2023-09-26

可能的重复项:
"这个"里面的对象

我正在

尝试为我正在处理的 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对象),正如你所看到的,它向下层叠的方式,旨在成为一种短手技术。例如,如果你想定义所有角都相同,你会使用{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;
                }
            }

晚餐很草率,但嘿,它奏效了!谢谢你的帮助!我选择了答案,因为这个解释导致我这样做!

"当我引用defaults.top它是undefined"

这是因为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

显然,后者更适合将某些属性设置为一个值,将其他属性设置为另一个值。(尽管在您的示例中,所有属性都是相同的。

无论哪种方式,最终都会为您提供相同的对象(对象文字只是创建对象的快捷方式)。

"我希望它足够简单,可以做这样的事情$(selector).myPlugin({r:10});$(selector).myPlugin({top:10, bottom: 5});

好吧,您仍然可以使用对象文字作为参数来调用插件。但是defaults对象(我假设是在插件中定义的)可以使用其他技术定义。