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

时间:2012-04-12 08:48:44

标签: javascript jquery this member-variables

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

( function($) {

    $.fn.main = function() {

        this.setting = 1;

        $("#someElement").scroll( function() {

            console.debug(this.setting);

        } );

    }

} )(jQuery);

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

4 个答案:

答案 0 :(得分:3)

this动态获取其值时,this的值无法固定在闭包中。

尝试:

var self = this;

并引用自我。

答案 1 :(得分:1)

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

即可
( function($) {

    $.fn.main = function() {

        this.setting = 1;
        var that = this;
        $("#someElement").scroll( function() {

            console.debug(that.setting);

        } );

    }

} )(jQuery);

答案 2 :(得分:0)

( 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);

答案 3 :(得分:0)

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