javascript - Getting the object instance from a prototype -


I am trying to reach members of an object from within an object function. Sorry if I'm doing the wrong thing, then I'm starting one :)

I have something like this:

  function my object {canvas} {this. Value = 'hello world'; This.canvas = canvas; This.canvas.addEventListener ('mousemove', this.mouseMove); } MyObject.prototype.mouseMouse = function (evt) {// This canvas is hostile reference = this.getContext ('2d'); Context.fillText (/ * How to get the value of MyObject? * /, 0, 0); }   

Thanks.

Callback function needs to be called in context of the object example you can use for modern browsers , Which is bound to a particular context, which returns the function:

  this.canvas.addEventListener ('mousemove', this.mouseMove.bind (this));   

In simple words, when a call is made from MyObject.prototype.mouseMove to addEventListener , this value > function, the canvas example would be the value of the MyObject example instead of this .

To get around this, we pass a function which is a cover for the function that we really want to call this.mouseMove.bind (this) Creates a new function that hides the mouseMove function, so that the this value canvas instead of the object instance.

An alternative way to do this is to create an anonymous function wrap:

  ... var self = this; This.canvas.addEventListener ('mousemove', function (e) {self.mouseMove (e);});   

The disadvantage in this format is that you need to know how many logic passes are passed to the function, they pipe into the internal function call.

It is as follows:

  var itself = this; This.canvas.addEventListener ('mousemove', function () {// logic ARGUs = Array.prototype.slice.call in an array for cross-browser compatibility; back self; MouseMove.apply (self, args );});   

Now if you write that type of code, you will realize that there is an easy way to get the variables out, you only have one function and one reference and you can generate one the cover. That is what the function.prototype.bund does.

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -