我正在为 Google map v2 创建一个控件。在创建控件时,我发现了设计挑战并希望找到合适的解决方案。这是 cargo 。
自定义 Google 控件继承自 GControl;
myControl.prototype = new GControl();
接下来我需要重载初始化程序,所以就在这里。
myControl.prototype.initilize = function (map) {
//do some work and return stuff
};
现在,在我的自定义控件 initlize 函数中,我创建了几个元素,使用 GEvent 类订阅各种事件。为了使我的回调函数易于管理,我将它们包含到控件原型(prototype)中。
myControl.prototype.onEvent = function(e){
//do some work;
//modify the members of the current myControl instance
};
在我的回调函数“onEvent”中,我想修改我控件内的成员。 从函数访问控件的最佳方式是什么? 不能使用关键字“this”,因为它是对被单击元素的引用,在我的例子中是 div。而且我无法通过原型(prototype)访问成员,因为我需要该对象的特定实例。我考虑过的唯一可行的解决方案是在我的一个脚本中全局创建我的控件。这是最好的方法吗?
最佳答案
我能想到的最简单的事情是在构造函数中定义 onEvent
方法,这样您就可以快速访问当前对象实例,并且无需修改公共(public) API :
function MyControl () {
var instance = this; // store a reference to 'this'
this.onEvent = function (e) {
// use the instance variable
instance.otherMethod();
};
}
请注意,在这种方法中,onEvent
属性将物理存在于您的对象实例中 (obj.hasOwnProperty('onEvent') = true
)。
编辑:您只需使用 GEvent.bind
功能:
GEvent.bind(map, "click", myObj, myObj.onEvent);
上述 bind
方法将强制执行上下文,因此 myObj.onEvent
中的 this
关键字将指向 myObj
对象实例当事件被触发时,它将毫无问题地与您的代码一起使用。
关于JavaScript 对象继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2175129/