【问题标题】:Call private function when passing function as argument in function?在函数中将函数作为参数传递时调用私有函数?
【发布时间】:2011-11-14 19:25:51
【问题描述】:

我正在创建一个 javascript 框架,但下面的代码由于某种原因无法正常工作。有什么原因吗?

function jCamp(code){
   function test(){
      alert();
   }
  code();
}
jCamp(function(){
  test();
});

【问题讨论】:

    标签: javascript function frameworks private


    【解决方案1】:

    您可以通过 call 或 appy 更改范围:

    function jCamp(code){
       function test(){
          alert();
       }
      code.call(test);
    }
    jCamp(function(){
      this();
    });
    

    所以我们把this改成引用私有函数

    【讨论】:

      【解决方案2】:
      在作为 jCamp() 参数的匿名函数内部调用的

      test() 未定义(如果您不更改,那就是第 8 行的那个你的代码)。 test() 函数只定义在 jCamp() 的定义中。

      【讨论】:

      • 那么有没有办法让函数只能通过 jCamp() 的参数函数调用?
      【解决方案3】:
      function jCamp(code){
         this.test = function(){
            alert("test");
         }
        code();
      }
      jCamp(function(){
        this.test();
      });
      

      我会这样做。

      【讨论】:

        【解决方案4】:

        test 是一个私有函数,只能在jCamp 内使用。您不能从作为参数传递的匿名函数中调用它。不过,您可以将其设为属性,如下所示:

        function jCamp(code){
           this.test = function(){
              alert();
           }
          code();
        }
        jCamp(function(){
          this.test();
        });
        

        【讨论】:

        • 请注意,这实际上会在全球范围内存储test,因为thiswindow
        【解决方案5】:

        函数的范围是在创建时确定的,而不是在调用时确定的。

        var a = 1; // This is the a that will be alerted
        function foo(arg) {
                var a = 2;
                arg();
        }
        foo(function () { alert(a); });
        

        【讨论】:

          猜你喜欢
          • 2020-02-17
          • 2021-12-29
          • 1970-01-01
          • 2019-02-22
          • 1970-01-01
          • 2019-12-28
          • 2021-04-13
          • 2013-01-27
          • 1970-01-01
          相关资源
          最近更新 更多