自定义对象中的变量范围

Variable scope in a custom object

本文关键字:变量 范围 对象 自定义      更新时间:2023-09-26

我需要从函数enableNav访问 buttons 属性,但我的问题是我不能,因为this引用指向enableNav函数而不是对象本身,如何正确获取buttons

(function() {
var MyCustomObject = {
    init: function(config) {
        this.myvar = config.myvar;
        this.buttons = config.buttons;
        this.enableNav();
    },
    enableNav: function() {
       // need to use buttons here!!
    }
};
MyCustomObject.init({
    myVar: 3,
    buttons: $('button')
});
})();

this参考指向enableNav函数

不,它没有。

你在这里称之为:

this.enableNav();

所以在enableNav内部,this将是this在那条线上的任何价值。

(因为,假设没有使用new,当你调用foo.bar.baz()时,baz会因其this谷而bar)。

所以:

enableNav: function() {
   this.buttons.append(foo); // or whatever
}