Skip to content Skip to sidebar Skip to footer

Accessing "this" Type Javascript Variables From Other Functions

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

Solution 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.

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

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

Solution 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.

Post a Comment for "Accessing "this" Type Javascript Variables From Other Functions"