在构造函数中绑定方法
Binding a method within a constructor
我正在尝试创建一个类,并将其传递给另一个类,我遇到了原型问题。我知道我可以使用bind
来解决这个问题,但我无法找到一种方法来将原型方法绑定到实例化时的构造函数。这样就剩下了这样的内容:
foo = new obj(); // has foo.method that depends on "this" being bound to obj
// pass foo.method to bar, with it's context bound to foo
bar = new obj2(foo.method.bind(foo)); // obj2 uses foo.method as a "callback" internally. ugly. T_T
下面是一个做作的例子:
/**
* Base horn class. To be shared by cars, clowns, braggads, etc.
*/
var Horn = (function(){
var Horn = function (noise){
this.noise = noise;
};
Horn.prototype.sound = function(){
return "*blowing horn* " + this.noise;
};
return Horn; // is there a way to bind here?
})();
/**
* Base car class. Needs a horn.
*/
var Car = (function(){
var Car = function (model, horn) {
this.model = model;
this.horn = horn;
};
Car.prototype.drive = function(){
return "i'm driving in my " + this.model + " " + this.horn();
};
return Car;
})();
/*
* Visualize output
*/
var term = document.getElementById('term');
term.say = function(message){
this.innerHTML += message + "'n";
};
// create a horn for cars.
var carHorn = new Horn('beep beep');
term.say(carHorn.sound()); // *blowing horn* beep beep
// pass the horn to a new Acura
var acura = new Car("acura", carHorn.sound);
term.say(acura.drive()); // i'm driving in my acura *blowing horn* undefined
// Pass the horn to a prius, but bind the horn first
var prius = new Car("prius", carHorn.sound.bind(carHorn)); // whooo bind.
term.say(prius.drive()); //i'm driving in my prius *blowing horn* beep beep
JS本
我读了很多关于SO的文章(这篇文章很有帮助),但我似乎找不到一个优雅的方法来做到这一点。
还有,如果我用了完全相反的方法,请让我知道。
可以在构造函数中绑定方法:
var Horn = function (noise){
this.noise = noise;
this.sound = this.sound.bind( this );
};
RHS将从原型中读取它,LHS将直接写入它在对象上,当你引用原型时,它会在原型上产生阴影。您仍然可以使用hornInstance.constructor.prototype.sound
或Horn.prototype.sound
引用未绑定的版本。
这通常是在你没有选择的时候做的,比如在传递一个方法的时候作为某个地方的事件侦听器。在这种情况下,你可以很容易地通过
我通常会传递整个对象或函数输出,如问题的评论中所建议的那样。然而,你所要求的是可能的。你只是不能在原型中拥有这些函数,你需要为每个实例单独(绑定)一个函数:
var Horn = (function(){
var Horn = function (noise){
this.noise = noise;
this.sound = function(){
return "*blowing horn* " + this.noise;
}.bind(this); // bind here
};
return Horn;
})();
http://jsfiddle.net/5xcHG/相关文章:
- 将对象的方法绑定到元素的事件
- 将类方法绑定到类外绑定的事件处理程序内的AJAX成功回调
- bind():您正在将一个组件方法绑定到该组件.React会自动为您执行此操作
- JS方法绑定与2个不同的这个
- backbonejs:不能调用未定义的方法“绑定”
- 将所有方法绑定到“this”
- 内联方法绑定是一种不好的做法
- 如何使用 jQuery 和静态页方法绑定控件数据
- 在Javascript中,有没有一种简洁的方法可以将方法绑定到对象
- 如何将多个方法绑定到单个事件
- 监视一个方法与西农.方法绑定到事件侦听器.方法已执行,但.calledOnce为false
- Javascript OOP:将方法绑定到事件处理程序
- “this"当方法绑定到事件侦听器时未定义
- 如何将参数传递给绑定方法?绑定与匿名方法
- 将c++的虚方法绑定到具有覆盖能力的js中
- Backbone.js集合方法绑定
- 为什么我必须为React组件类中定义的方法绑定(this),而不是在常规ES6类中
- 了解AngularJS指令方法绑定是否默认为angular.noop
- 主干任务示例方法绑定
- 将带有参数的方法绑定到主干模型更改事件