【问题标题】:Writing Callback functions with preset Parameters使用预设参数编写回调函数
【发布时间】:2014-01-29 19:29:51
【问题描述】:

功能

var Q = {
   each:function(func){
     if(func && typeof func == 'function'){
        var len = this.length;
        for(i=0;i<len;i++){
          this[i];
       }
     }
   }
};

我如何在上面的例子中编写一个回调函数,以便我可以在 for loop 中执行类似 jQuery 的函数

前:

 _$('element').each(function(n,i){
       if(i==3){
         _$(this[i]).hide();
       }
 });

然后是其他可以进一步深入的实例。我知道我可以通过设置简单地写一个回调

功能

var Q = {
   each:function(func){
     if(func && typeof func == 'function'){
        var len = this.length;
        for(i=0;i<len;i++){
          this[i];
          //func(); OR func.call(this,[i,n]);
       }
     }
   }
};

没有经常使用 apply 或 call ,老实说,文档现在有点难以理解。我相信我写的调用函数是正确的。

【问题讨论】:

    标签: javascript callback call apply


    【解决方案1】:

    随着我不断练习,我已经想出了如何简单地写这个。

    var Q = {
      each:function(func){
       if(func && typeof func == 'function'){
         var len = this.length;
         for(i=0;i<len;i++){
           func.call(this,i,this[i]);
         }
        }
       }
    };
    

    然后可以这样写

     Q.each(function(i,x){
        if(x.id=="someRandomID" || i = 4){
          this.style.display="none";
        }
    });
    

    虽然我知道使用 call 或 apply 我们保留了 this 运算符,但我无法具体解释调用的作用。

    【讨论】:

      猜你喜欢
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多