Passing a pointer to objects method safely to goog

2019-08-10 08:53发布

问题:

When passing a method pointer to google.maps.event.addListener, google maps seems to overwrite it's this reference with an instance of google.maps.Map, therefore it renders it useless if the methods references any of its prototype memebers internally.

The long story short, if I pass myObj.MyMethod as an event callback, at the time of its execution MyMethod.this reference will be an instance of google.maps.Map rather then myObj.

Is there any way to safely pass a method pointer to addListener and maintain all of its references intact ?

Many thanks !

回答1:

When you passed the method with addListener(), The passed object of method would be lost at event occurred, so as a result method is not defined, you should call the method something like

google.maps.event.addListener('someEvent', function (){
     myObj.MyMethod.call(myObj); //invoked MyMethod with reference myObj

    //myObj.MyMethod.apply(myObj); <= you can use apply method also
})