【问题标题】:Simple solution for using 'this' instead of '_this/self/$this' in callback function在回调函数中使用 'this' 而不是 '_this/self/$this' 的简单解决方案
【发布时间】:2016-12-03 08:31:12
【问题描述】:

我想在回调函数中去掉 _this/self/$this 辅助变量。我写:

export class someClass {
  someFunction = function( ) {
    this.foo = "bar";
    this.anotherClass.doSomething( this, function( foo ) {
       console.log( this.foo, "/", foo );  // "bar / another bar"
    } );
  }
}

export class anotherClass {
   anotherFoo: string = "another bar";

   doSomething( _this, cb ) {
      cb.call( _this, this.anotherFoo );
   }
}

有没有更简单的方法来做到这一点?我想去掉'this'参数。

【问题讨论】:

    标签: javascript callback this


    【解决方案1】:

    您可以使用arrow function 来传递回调:

    class someClass {
      constructor() {
        this.anotherClass = new anotherClass();
      }
    
      someFunction() {
        this.foo = "bar";
        this.anotherClass.doSomething(foo => {
          console.log( this.foo, "/", foo );
        });
      }
    }
    
    class anotherClass {
      anotherFoo: string = "another bar";
    
      doSomething(cb) {
        cb(this.anotherFoo);
      }
    }
    

    【讨论】:

    • 这是一种将当前上下文绑定到this 的花哨且更具可读性的方式。至于编译器,没有任何变化:)
    • @MehmetBaker .bind() 真的很慢,而且现在大多数 JS 引擎都原生支持箭头函数,内部创建的速度要快得多。
    • 我不知道,我会调查一下。如果这是真的,那么您的方式确实是我认为最准确的答案:)
    • 实际上最快的方法似乎是使用_thisjsperf.com/arrow-function-vs-bind-vs-context-argument/4 所以既然 OP 想要更多可读的代码,这种方式还是比较好。
    【解决方案2】:

    您可以使用Function.prototype.bind修改您的代码

    这将允许您将特定上下文绑定到函数。

    欲了解更多信息:https://developer.mozilla.org/tr/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    export class someClass {
      someFunction = function( ) {
        this.foo = "bar";
        var callback = function(foo) {
          console.log(this.foo, '/', foo);
        };
    
        this.anotherClass.doSomething(callback.bind(this));
      }
    }
    

    export class anotherClass {
      anotherFoo: string = "another bar";
    
      doSomething(cb) {
        cb(this.anotherFoo);
      }
    }
    

    【讨论】:

    • 我想将范围保留在被调用的函数中。我只想在回调中有调用函数的 this 值,而不是被调用函数的 this 值。
    • 我无法完全弄清楚您要做什么。我添加了一些代码。当 someClass 调用 doSomething 时,它使用 someClass 的范围来调用它。所以 anotherClass 中的 doSomething 总是会调用它所绑定的范围的回调。
    • 我明白,但就我而言,我需要 doSomething() 函数中的原始范围。我不想改变它。因此参数_this。我只是觉得可能有一个更简单的解决方案,将 this 保留在被调用的函数中并将其保留在回调中。但也许没有。
    • 所以我更新了我的答案。现在回调函数直接绑定到 someClass 的上下文。当通过 doSomething 调用它时,它会保留它的上下文。
    • 是的。这就是我要找的东西。
    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多