Accessing “this” Type JavaScript Variables From Other Functions

好久不见. 提交于 2019-12-12 04:58:22

问题


I have an event firing and even though it's inside of the function from which I'm trying to access variables, I get Uncaught TypeError: Cannot read property '...' of undefined. So, let's say:

( function($) {

    $.fn.main = function() {

        this.setting = 1;

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

            console.debug(this.setting);

        } );

    }

} )(jQuery);

I'm sure it has something to do with timing, but then again, I could be wrong. Should I make a copy of this and make that public? Anyone? Thanks.


回答1:


The value of this cannot be pinned in a closure as the this gets its value dynamically.

try :

var self = this;

And reference self.




回答2:


Just copy this to another variable

( function($) {

    $.fn.main = function() {

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

            console.debug(that.setting);

        } );

    }

} )(jQuery);



回答3:


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

If you want to use the this from $.fn.main, you can store the variable. The following would work:

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



回答4:


the this inside the scroll method is refereing to the scroll method. The method is bound to be called on the scroll event of element with id 'someElement'. and the scope of the binding object is lost.



来源:https://stackoverflow.com/questions/10120271/accessing-this-type-javascript-variables-from-other-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!