Gabriel Ryan Nahmias
Gabriel Ryan Nahmias

Reputation: 2159

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

Upvotes: 0

Views: 142

Answers (4)

Peter Aron Zentai
Peter Aron Zentai

Reputation: 11740

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

try :

var self = this;

And reference self.

Upvotes: 3

Satish N Ramteare
Satish N Ramteare

Reputation: 197

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.

Upvotes: 0

Florian Margaine
Florian Margaine

Reputation: 60747

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

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

Just copy this to another variable

( function($) {

    $.fn.main = function() {

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

            console.debug(that.setting);

        } );

    }

} )(jQuery);

Upvotes: 1

Related Questions