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 ?
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…
Another solution is to declare a variable and set its value to this.hello, like this :