-1

我正在编写帮助函数来遍历所有数组元素 - 只是为了学习 js。

这是代码:

function arrayLoop(array, func){

    var ar = array.length,
        i=0;

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

};

当我像这样使用它时它正在工作:

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

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

但是当我尝试在对象内部执行此操作并想要使用此上下文时 - 发生错误:

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 

  };  

};

如何将父级自动传递给arrayLoop函数?

4

4 回答 4

2

您可以更改 arrayLoop 以允许上下文参数:

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值,然后在调用回调时为您设置它,它将在所有浏览器.bind()中工作(在旧浏览器中不起作用)。

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.

于 2013-03-30T10:24:36.173 回答
1

您可以在闭包中捕获它:

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

或使用以下.bind()功能:

test.prototype.find = function() {
    arrayLoop(this.foo, function(i) {
        alert(this.bar[i]);
    }.bind(this));
};
于 2013-03-30T10:17:42.853 回答
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

于 2013-03-30T10:28:06.457 回答
0

将函数绑定到对象:

test.prototype.find = function(){

  arrayLoop(this.foo, function(i){

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

  }.bind(this));  

};
于 2013-03-30T10:24:05.777 回答