Passing a pointer to objects method safely to google.maps.event.addListener

会有一股神秘感。 提交于 2019-12-11 09:19:43

问题


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
})


来源:https://stackoverflow.com/questions/22436596/passing-a-pointer-to-objects-method-safely-to-google-maps-event-addlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!