Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 858
Ledivin Avatar asked Dec 20 '22 17:12

Ledivin


2 Answers

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
}
like image 103
jfriend00 Avatar answered Dec 23 '22 06:12

jfriend00


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));
};
like image 21
jackwanders Avatar answered Dec 23 '22 06:12

jackwanders