Tuesday, 15 July 2014

javascript - Binding a method within a constructor -


I am trying to create a square, and passing it to another class, and with the prototype Running into problems. I know that I can use the bind to get around this, but I can not initially understand a way to combine the prototype method for its creator. It leaves me something like this:

  foo = new obj (); // is foo.method which is bound to "this" which is bound to obj // pass foo.method, in this context foo bar = new obj2 (foo.method.bind (foo)) is bound; // obj2 uses foo.method internally as "callback" ugly. T_T   

Here is a customized example:

  / ** * Base horn class. Car, joker, braggad, 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 square one horn is needed * / var car = (function () {var car = function (model, horn) {this.model = model; this.horn = horn;}; car. Draw = function () {return "I'm running my" + this.model + "" + this.horn ();}; return car;}) (); / * * Visual output * / var term = document.getElementById ('term'); Term.say = function (message) {this.inner html + message = "\ n"; }; // Create a horn for cars Var Carhoron = New Horn ('Beep beep'); Term.say (carHorn.sound ()); // * Fly horn * Beep beep / pass a new Acura var acura = new car ("Acura", Carhorna sound); Term.say (acura.drive ()); // I'm playing in my acura * blowing horn * undefined // pass a horn in a prese, but the horn is tied to the varian = new car ("preece", carhorn, sound.bind (carhorn) for the first time. Take; // Jou Bind term.say (prius.drive ()); // I'm flying in my prize * blowing horn * beep beep   

I've read a lot (the post was quite useful ), But I can not find a great way to do this.

In addition, if I'm going backwards about it completely, then tell me

You can tie a method within a constructor:

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

The RHS will teach it with prototype and LHS will write it directly on the object and when you refer to it it will be shadowed on the prototype. You can still refer to the unbound version with hornInstance.constructor.prototype.sound or horn.prototype.sound .

This is usually done when you have no choice but to go somewhere in the form of an event listener, in this case you can easily pass the object to the horn object only.

No comments:

Post a Comment