Reputation: 2591
Let us presume I have the following object defined:
var myObj = function(){
this.hello = "Hello,";
}
myObj.prototype.sayHello = function(){
var persons = {"Jim", "Joe", "Doe","John"};
$.each(persons, function(i, person){
console.log(this.hello + person);
}
}
Problem is that inside $.each this refers to person but I would like to access the obj property hello.
The only solution which i could find was declaring in sayHello function something like
var _this = this;
and then in $.each i would use something like
console.log(_this.hello + person);
But unfortunately, this is not very good code. Is there another way to resolve this problem elegantly ?
Upvotes: 1
Views: 264
Reputation: 1656
That doesn't seem to be a bad solution... Perhaps you would be more interested in using Function.bind (see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind#Compatibility for compatibility), but that leads to counter-performance...
var myObj = function(){
this.hello = "Hello,";
}
myObj.prototype.sayHello = function(){
var persons = ["Jim", "Joe", "Doe","John"];
$.each(persons, function(i, person){
console.log(this.hello + person);
}.bind(this) );
}
Another solution is to declare a variable and set its value to this.hello, like this :
var myObj = function(){
this.hello = "Hello,";
}
myObj.prototype.sayHello = function(){
var persons = ["Jim", "Joe", "Doe","John"],
hello = this.hello;
$.each(persons, function(i, person){
console.log(hello + person);
});
}
Upvotes: 3
Reputation: 154
A corrected example, satisfyng your demand on a correctly set this is
myObj.prototype.sayHello = function(){
var persons = ["Jim", "Joe", "Doe","John"];
persons.forEach(function(person){
console.log(this.hello + person);
},this);
}
Check out Array.forEach for more info.
Upvotes: 3
Reputation: 49929
If you don't define the variable outside your $.each scope, it can not be found. You have to do define outside your $.each function to make it possible to call. Otherwise it will be a undefined object.
If you want to define a reference, please check out the following URL: Pass additional parameters to jQuery each() callback
Upvotes: 0