我正在尝试创建一个类,并将其传递给另一个类,但我遇到了原型问题。我知道我可以用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
我已经阅读了很多关于 SO(这篇文章很有帮助),但我似乎找不到一种优雅的方式来做到这一点。
另外,如果我要以完全倒退的方式进行此操作,请告诉我。