【问题标题】:Call javascript function with bind使用绑定调用 javascript 函数
【发布时间】:2019-01-30 00:34:51
【问题描述】:

我有这个功能:

$(this.myObject).click(A.bind(this));
function A(){
     //  stuff here
}

我想在第二个函数中调用(绑定 this)。

$(this.myOtherObject).click(B.bind(this));
function B(){
      A();             //  works but does not bind
      A.bind(this);    //  does not work
}

我该怎么做?

【问题讨论】:

  • bind 不调用/执行方法....
  • 请查看 MDN 文档以了解绑定:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。如果您想调用该函数,可以使用.call 或.apply,通过提供this 作为两者的第一个参数。否则,使用.bind,然后显式调用函数。
  • this.myObject 属于全局窗口对象吗?
  • bind() 返回一个稍后执行的函数。让 X = A.bind(this); X();

标签: javascript function binding


【解决方案1】:
function B(){
    A();             //  works but does not bind
    A.bind(this);    //  does not work
}

bind 用于创建绑定到上下文的新函数(请参阅bind documentation)。如果你这样做,你需要调用新函数:

A.bind(this)();

但是,您应该使用 call method 或 apply method 直接调用具有特定上下文的函数:

A.call(this);
A.apply(this);

【讨论】:

    【解决方案2】:

    您想使用 call(this) 而不是 bind() 因为 bind() 只是返回方法。

    A.call(this)
    

    【讨论】:

      猜你喜欢
      • 2019-07-14
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 2015-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多