使用'这个'的简单解决方案而不是' _this / self / $ this'在回调函数中

时间:2016-12-03 08:31:12

标签: javascript callback this

我想在回调函数中摆脱_this / self / $这个辅助变量。我写道:

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 );
   }
}

有更简单的方法吗?我想摆脱这个'这个'参数。

2 个答案:

答案 0 :(得分:2)

您可以使用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);
  }
}

答案 1 :(得分:1)

您可以使用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);
  }
}