在构造函数中绑定方法

Binding a method within a constructor

本文关键字:方法 绑定 构造函数      更新时间:2023-09-26

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