0

假设我有以下内容:

function test() {
     this.message = "Hello World";
     this.marker = //A google marker object
     google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
         alert(this.message); // Incorrect as "this" refers to this.mypolygon
     });     
}

如何使我可以正确地在事件侦听器中提醒“Hello World”?换句话说,从事件监听器中获取“this”的正确上下文?

4

2 回答 2

1

您将需要关闭。

function test() {
     var self = this;
     this.message = "Hello World";
     this.marker = //A google marker object

     google.maps.event.addListener(this.marker,'click', function(mouseEvent) {
         alert(self.message); // Now "self" points to parent function scope
     });     
}
于 2013-04-04T20:06:17.570 回答
0

不要使用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); 
     }     
}
于 2013-04-04T19:37:37.750 回答