从其他函数访问“this”类型JavaScript变量

我有一个事件触发,即使它在我试图访问变量的函数内部,我得到Uncaught TypeError: Cannot read property '...' of undefined 。 所以,让我们说:

 ( function($) { $.fn.main = function() { this.setting = 1; $("#someElement").scroll( function() { console.debug(this.setting); } ); } } )(jQuery); 

我确定它与时间有关,但话又说回来,我可能是错的。 我应该复制一份并将其公之于众吗? 任何人? 谢谢。

这个值不能固定在一个闭包中,因为this会动态获取它的值。

尝试:

 var self = this; 

并参考自我。

只需将其复制到另一个变量

 ( function($) { $.fn.main = function() { this.setting = 1; var that = this; $("#someElement").scroll( function() { console.debug(that.setting); } ); } } )(jQuery); 
 ( function($) { $.fn.main = function() { this.setting = 1; // "this" refers to the "$.fn.main" object $("#someElement").scroll( function() { console.debug(this.setting); // "this" refers to the "$('#someElement')" object } ); } } )(jQuery); 

如果要使用$.fn.main ,可以存储变量。 以下方法可行:

 ( function($) { $.fn.main = function() { var that = this that.setting = 1; // "this.setting" would also work $("#someElement").scroll( function() { console.debug(that.setting); // You need to reference to the other "this" } ); } } )(jQuery); 

scroll方法中的this引用了scroll方法。 该方法必须在id为’someElement’的元素的scroll事件上调用。 并且绑定对象的范围丢失。