【问题标题】:Javascript objects and passing member functions as parametersJavascript 对象并将成员函数作为参数传递
【发布时间】:2012-03-07 10:58:34
【问题描述】:

这很难解释,如果我写一些示例代码可能会更好:

function A()
{
    this.b = new B();

    this.a_value = 456;

    this.f = function(i)
    {
        for(var i = 0; i < this.a_value; ++i)
            DoStuff(i);
    }

    this.b.C(this.f)
}

我试图将一个函数作为参数传递给 B,但是当 C 试图达到 a_value 时,它​​是未定义的。我该如何解决?

我希望我没有把我的问题过于简单化。

【问题讨论】:

    标签: javascript function object arguments


    【解决方案1】:

    使用箭头函数实现相同目的的另一种方法。由于箭头函数不绑定this,它将保留定义函数时的任何值。

    function A()
    {
        this.b = new B();
    
        this.a_value = 456;
    
        this.f = i =>
        {
            for(var i = 0; i < this.a_value; ++i)
                DoStuff(i);
        }
    
        this.b.C(this.f)
    }
    

    【讨论】:

      【解决方案2】:

      现在(或者显然是从 2015 年开始),您还可以将函数绑定到对象实例,如 in this answer 所示:

      this.b.C(this.f.bind(this));
      

      作为解释:

      var fn = myObject.myFunction.bind(myObject);
      
      // The following two function calls are now equivalent
      fn(123);
      myObject.myFunction(123);
      

      【讨论】:

      • 优秀的答案!其他答案求助于使用随机命名变量来存储this,它可以工作,但在大型长期代码库中不是很容易维护
      【解决方案3】:

      您可以将this.f 传递给函数c,但要正确调用它,您还需要像这样传递this 的值:

      function A()
      {
          this.b = new B();
      
          this.a_value = 456;
      
          this.f = function(i)
          {
              for(var i = 0; i < this.a_value; ++i)
                  DoStuff(i);
          }
      
          this.b.C(this.f, this)   // <== pass "this" here
      }
      
      And, then in `this.b.c`:
      
      ...b.c = function(fn, context) {
         fn.call(context);      // <== use .call() here to apply the right this value
      }
      

      【讨论】:

        【解决方案4】:

        问题是this 没有绑定到 JavaScript 中的任何固定值。您可以使用闭包来解决此问题,这可能是这种情况下最好的方法:

        function A()
        {
            var that = this;
        
            this.b = new B();
        
            this.a_value = 456;
        
            this.f = function(i)
            {
                for(var i = 0; i < that.a_value; ++i)
                    DoStuff(i);
            }
        
            this.b.C(this.f);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-03-17
          • 2018-02-23
          • 2012-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-27
          • 2012-06-12
          相关资源
          最近更新 更多