1

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 ?

1
  • var persons = {"Jim", "Joe", "Doe","John"}; - this is incorrect, you should use an array instead. And you don't really need $.each here. Commented Nov 21, 2011 at 12:37

3 Answers 3

3

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);
     });
}
1
  • Thank you for your great answer, I had an argument with a guy who thinks he's a guru in jquery and he said that my solution is bad code. Now that 3 people have confirmed what I have already known I feel much more comfortable with my knowledge.
    – user253530
    Commented Nov 21, 2011 at 12:39
3

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.

0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.