在回调中可以替代function.prototype.bind

Alternative to function.prototype.bind in callback

本文关键字:function prototype bind 回调      更新时间:2023-09-26

我试图避免在项目中使用function.prototype.bind。我不想使用多边形

考虑下面的代码,有没有一种方法可以避免

  this.foo = new Obj2(this.callme.bind(this));

在下面的场景?:

function Obj1(){
  this.value = 1;
  this.foo = new Obj2(this.callme);
  this.foo.doSomething();
}
Obj1.prototype.callme = function(){
   console.log(this.value);
}
function Obj2(callback){
   this.finished = callback;
}
Obj2.prototype.doSomething = function(){
   // Do something here
   this.finished();// obj2 will be in scope. Obj1.value will not be availble
}
var bar = new Obj1()

您可以创建一个新的闭包来避免使用bind():

var self = this;
this.foo = new Obj2(function() { self.callme(); });

不写额外的/可以说更混乱的代码-这种事情是bind的存在。作为dsh答案中基于闭包方法的替代方法,您可以将上下文传递给另一个对象使用:

function Obj1(){
  this.value = 1;
  this.foo = new Obj2(this.callme, this);
  this.foo.doSomething();
}
Obj1.prototype.callme = function(){
   console.log(this.value);
}
function Obj2(callback, context){
   this.finished = callback;
   this.context = context;
}
Obj2.prototype.doSomething = function(){
   // Do something here
   this.finished.call(this.context);
}
var bar = new Obj1()

这就是某些标准函数(如Array.prototype.some)的工作方式,您可以在回调中指定要使用的对象作为this。您可能想要编码Obj2,因此上下文是可选的,这取决于您的需要。