自定义对象中的变量范围

时间:2012-06-04 10:18:28

标签: javascript jquery object scope

我需要从函数buttons访问enableNav属性,但我的问题是我不能,因为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') }); })();

{{1}}

1 个答案:

答案 0 :(得分:0)

  

this参考指向enableNav函数

不,不。

你在这里叫它:

this.enableNav();

因此,在enableNav内,this将是this在该行上的任何值。

(因为,假设未使用new,当您致电foo.bar.baz()时,baz会因bar的价值获得this

这样:

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