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

Accessing "this" Type JavaScript Variables From Other Functions

本文关键字:类型 JavaScript 变量 this 其他 函数 访问      更新时间:2023-09-26

我有一个事件触发,即使它在我尝试从中访问变量的函数内部,我也得到了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);

如果要使用 $.fn.main 中的this,可以存储变量。以下方法将起作用:

( 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正在引用滚动方法。该方法必然会在 id 为 'someElement' 的元素的滚动事件上调用。并且绑定对象的作用域将丢失。