1

我正在尝试创建一个类,并将其传递给另一个类,但我遇到了原型问题。我知道我可以用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 Bin

我已经阅读了很多关于 SO(这篇文章很有帮助),但我似乎找不到一种优雅的方式来做到这一点。

另外,如果我要以完全倒退的方式进行此操作,请告诉我。

4

2 回答 2

1

您可以在构造函数中绑定方法:

var Horn = function (noise){
    this.noise = noise;
    this.sound = this.sound.bind( this );
};

RHS 将从原型中读取它,而 LHS 将直接将其写入对象上,并且当您引用它时它会在原型上隐藏它。您仍然可以使用hornInstance.constructor.prototype.sound或引用未绑定的版本Horn.prototype.sound

这通常是在您别无选择时完成的,IE 将方法作为事件侦听器传递到某处时。在这种情况下,您可以轻松地传递喇叭对象。

于 2013-06-20T22:24:13.243 回答
0

我通常会按照问题评论中的建议传递整个对象或函数输出。但是,您要问的是可能的。您只是不能拥有原型中的函数,每个实例都需要一个单独的(绑定)函数:

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/

于 2013-06-20T22:24:25.927 回答