不要使用this
关键字。使用其他不会改变的东西addListener
:
function test() {
foo.message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(foo.message);
});
}
甚至更清洁:
function test() {
var message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(message);
});
}
或者,您可以这样做:
function test() {
this.message = "Hello World";
this.marker = //A google marker object
var self = this;
google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
alert(self.message);
});
}
最后,如果你真的想this
在点击处理程序中使用,你可以使用bind
:
function test() {
this.message = "Hello World";
this.marker = //A google marker object
google.maps.event.addListener(this.marker,'click', myFunc.bind(this) );
function myFunc(mouseEvent) {
alert(this.message);
}
}