5

As someone who is attempting to take a more object oriented approach to my javascript programming I've hit a stumbling block which I'm sure is probably something very basic, but, take the following object implementation (assume that the jQuery object is available to 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's each() function is iterating through
        console.log(this);

        //so, how can i access the Foo object's properties from here so i can do
        //something like this?
        this.myFunc();
    });
};

3 Answers 3

6

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

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

    var self = this;

    $('.some_elements').each(function()
    {
        self.myFunc();
    });
};
Sign up to request clarification or add additional context in comments.

Comments

5

Before you enter the function you pass to each, you need to capture this of the outer function in a variable and then use the variable inside of the function that you pass to 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();
    });
};

As you've found out, this inside of the function that you pass to each refers to the current item in the jQuery object on each iteration i.e. first iteration refers to item at property 0, second iteration refers to item at property 1, etc.

Comments

0

You're discovering the usefulness of JavaScript closures. They're incredibly powerful and useful for making concise code. This is one of the most useful JavaScript features you can try to understand.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.