Skip to content Skip to sidebar Skip to footer

Jquery Using This To Access Object Context When Inside Callback

Let us presume I have the following object defined: var myObj = function(){ this.hello = 'Hello,'; } myObj.prototype.sayHello = function(){ var persons = {'Jim', 'Joe',

Solution 1:

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);
     });
}

Solution 2:

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.

Solution 3:

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

Post a Comment for "Jquery Using This To Access Object Context When Inside Callback"