JavaScript scope issue

As a person who is trying to use a more object-oriented approach to my javascript programming, I hit a stumbling block, which I am sure is probably something very simple, but take the following implementation of the object (suppose the jQuery object is available for of this code):

function Foo()
{
    this.someProperty = 5;
}

Foo.prototype.myFunc = function()
{
    //do stuff...
};

Foo.prototype.bar = function()
{
    //here 'this' refers to the object Foo
    console.log(this.someProperty);

    $('.some_elements').each(function()
    {
        //but here, 'this' refers to the current DOM element of the list of elements
        //selected by the jQuery selector that jquery each() function is iterating through
        console.log(this);

        //so, how can i access the Foo object properties from here so i can do
        //something like this?
        this.myFunc();
    });
};
+5
source share
3 answers

You can temporarily use another variable to point to the correct one :

Foo.prototype.bar = function()
{
    //here 'this' refers to the object Foo
    console.log(this.someProperty);

    var self = this;

    $('.some_elements').each(function()
    {
        self.myFunc();
    });
};
+6
source

function, each, this , function, each.

function Foo()
{
    this.someProperty = 5;
}

Foo.prototype.myFunc = function()
{
    //do stuff...
};

Foo.prototype.bar = function()
{
    // in here, this refers to object Foo

    // capture this in a variable
    var that = this;

    $('.some_elements').each(function()
    {
        // in here, this refers to an item in the jQuery object
        // for the current iteration   

        console.log(that);
        that.myFunc();
    });
};

, this , each, jQuery , 0, 1 ..

+5

JavaScript. . JavaScript, .

0

All Articles