我试图避免在项目中使用function.prototype.bind
。我不想使用polyfill。
考虑下面的代码,有没有办法避免
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()
答案 0 :(得分:2)
您可以创建一个新的闭包以避免使用bind()
:
var self = this;
this.foo = new Obj2(function() { self.callme(); });
答案 1 :(得分:2)
不是没有编写额外的/可以说是更混乱的代码 - 这种事情就是bind
的用途。作为dsh's answer中基于闭包的方法的替代方法,您可以将上下文传递给另一个对象:
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
进行编码,因此上下文是可选的,具体取决于您的需求。