-1

I am writing helper function to loop through all array elements - just for learning js.

here is the code:

function arrayLoop(array, func){

    var ar = array.length,
        i=0;

    for ( i = 0; i < ar; i++ ){
        func(i);
    };

};

it is working when i use it like:

var foo = ['aa','bb','cc'];

arrayLoop(foo, function(i){
    alert(foo[i]);
});

but when i try to do it inside object and want to use this context - error occurs:

function test(){

   this.foo = ['aa','bb','cc'];
   this.bar = ['ff','gg','hh'];

}

test.prototype.find = function(){

  arrayLoop(this.foo, function(i){

     alert(this.bar[i])     //error- there is no this.bar 

  };  

};

How to pass parent this automatically to arrayLoop function ??

Kriss
  • 435
  • 1
  • 10
  • 22

4 Answers4

2

You can change arrayLoop to allow a context parameter:

function arrayLoop(array, ctx, func){
    ctx = ctx || window;
    var len = array.length, i = 0;
    for ( i = 0; i < len; i++ ) {
        func.call(ctx, i);
    }
}

test.prototype.find = function(){
  arrayLoop(this.foo, this, function(i) {
     alert(this.bar[i]);     // this will work
  });
}

This lets you pass in the desired this value for the callback and it will get set for you then when the callback is called and it will work in all browsers (.bind() doesn't work in older browsers).

FYI, you also were missing a ) in your find() function and you seem to like a number of extra semi-colons which do no harm, but don't need to be there.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

You could capture it in a closure:

test.prototype.find = function() {
    var self = this;
    arrayLoop(this.foo, function(i) {
        alert(self.bar[i]);
    });
};

or use the .bind() function:

test.prototype.find = function() {
    arrayLoop(this.foo, function(i) {
        alert(this.bar[i]);
    }.bind(this));
};
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

Use bind method.

test.prototype.find = function(){
    arrayLoop(this.foo, method.bind(this));
}

test.prototype.method = function(i){
    alert(this.bar[i]);
};

You can find an explanation why your code is not working here

Community
  • 1
  • 1
ShuklaSannidhya
  • 8,572
  • 9
  • 32
  • 45
0

Bind the function to the object:

test.prototype.find = function(){

  arrayLoop(this.foo, function(i){

     alert(this.bar[i])     //error- there is no this.bar 

  }.bind(this));  

};
Esailija
  • 138,174
  • 23
  • 272
  • 326