Ledivin
Ledivin

Reputation: 637

Javascript Object - using jQuery and this

When using jQuery methods within an object function (ie - .each()), the "this" variable is then referencing the object being iterated over. How can I access the Object's functions without "this"? I realize that's a bit confusing, so:

test.prototype.init = function(node) {
    node.children().each(function() {
        //call test.anotherFunction() here
        //Would normally call this.anotherFunction(), 
        //  but "this" refers to the current child.
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}

Help?

Upvotes: 4

Views: 105

Answers (3)

jackwanders
jackwanders

Reputation: 16040

You could also make use of the .bind function to change the context of the function. Whatever argument you provide to .bind will become the owner of the function when it executes, and thus, the value of this.

test.prototype.init = function(node) {
    node.children().each(function(i,el) {
        // this = test.prototype
        // i = index of the current child of `node`
        // el = HTML node of current child
        // $(el) = jQuery object representing current child
    }.bind(this));
};

Upvotes: 3

Chris Beemster
Chris Beemster

Reputation: 362

You can define the object that you want to refer to before iterating. You'll be able to approach it, as it's still in scope.

var currentObject = this;

test.prototype.init = function(node) {
    node.children().each(function() {
        currentObject.anotherFunction();
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}

Upvotes: 1

jfriend00
jfriend00

Reputation: 707736

Save a copy of this into a local variable (named self in this example, but you can name it anything you want) and use the saved copy in your embedded function:

test.prototype.init = function(node) {
    var self = this;
    node.children().each(function() {
        // use self here to reference the host object
    });
}
test.prototype.anotherFunction = function() {
    //whatever
}

Upvotes: 7

Related Questions