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?
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
}
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));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With