我想在回调函数中摆脱_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 );
}
}
有更简单的方法吗?我想摆脱这个'这个'参数。
答案 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);
}
}