[英]Accessing “this” Type JavaScript Variables From Other Functions
我有一个事件触发,即使它在我试图从中访问变量的函数内部,也会出现Uncaught TypeError: Cannot read property '...' of undefined
。 所以,我们说:
( function($) {
$.fn.main = function() {
this.setting = 1;
$("#someElement").scroll( function() {
console.debug(this.setting);
} );
}
} )(jQuery);
我确定这与计时有关,但话又说回来,我可能是错的。 我应该做的副本, this
并作出公开? 任何人? 谢谢。
值this
不能作为一个封闭寄托this
动态获取其值。
尝试:
var self = this;
并参考自我。
只需复制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);
如果你想使用this
从$.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);
在this
滚动内部方法refereing到滚动方法。 该方法势必在ID为“ someElement”的元素的滚动事件上调用。 并且绑定对象的范围丢失。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.