在回调中可以替代function.prototype.bind
Alternative to function.prototype.bind in callback
我试图避免在项目中使用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
,因此上下文是可选的,这取决于您的需要。
相关文章:
- 直接在函数声明上使用function.prototype.bind
- 如何通过 Function.prototype.apply() 更改调用函数的参数
- Function.prototype.call和Function.protoype.all只应用一个参数
- requestAnimationFrame的Function.prototype.bind导致属性不可读
- 对象如何获取 Function.prototype 方法
- Function.prototype上调用方法的性质
- 为什么在Function.prototype上没有原型属性
- Function.prototype.propertyname === Object.propertyname is t
- Function.prototype.apply:参数列表的类型错误
- node.js 使用 function.prototype.apply 执行的泛型函数
- Snippet usefulness - Function.prototype.call.bind(Function.p
- 使用 Function.prototype.bind.apply(Obj, args) 将参数传递给对象,只传递第一个元
- Function.prototype.call.bind 是如何工作的
- 在 Function.prototype.method 中返回它有什么作用
- JavaScript 中 Function.prototype 和 Object.prototype 之间的区别
- 使用 Function.prototype.bind 或保存的引用
- Phantomjs Function.prototype.bind
- Function.prototype.bind with null 作为参数
- Function.prototype.toMethod() 是做什么的
- Function.prototype.method what is prototype[name]