Javascript 在click事件中运行时,调用对象函数将未定义

Javascript 在click事件中运行时,调用对象函数将未定义,javascript,google-maps,Javascript,Google Maps,从我的对象PolygonExtend,我可以触发一些内部动作,比如显示和隐藏。这些行动似乎很有效。但是,当我在单击事件google.maps.event.addDomListener中运行相同的操作时,我得到一个TypeError:this.name未定义。我怎样才能让它工作 如上所述,如果尚未尝试此解决方案,请执行此操作 function PolygonExtend(name, path) { //this.name = name; var self = this;

从我的对象PolygonExtend,我可以触发一些内部动作,比如显示和隐藏。这些行动似乎很有效。但是,当我在单击事件google.maps.event.addDomListener中运行相同的操作时,我得到一个TypeError:this.name未定义。我怎样才能让它工作


如上所述,如果尚未尝试此解决方案,请执行此操作

function PolygonExtend(name, path) {
    //this.name = name;

    var self = this;
    this.name =  new google.maps.Polygon({
            path: path,
    });


    this.show = function() {
        self.name.setMap(map);
    };

    this.hide = function() {
        self.name.setMap(null);
    };

    return this.name.setMap(map); // makes Polygon show when instantiated
}

我不知道你想做什么。看起来像是在浪费代码,但看看这个:

function PointlessPolygon(map, coords){
  var t = this;
  this.map = map; this.coords = coords; this.showing = true;
  this.polygon = new google.maps.Polygon({paths:t.coords});
  this.show = function(){
    this.polygon.setMap(map); this.showing = true;
  };
  this.hide = function(){
    this.polygon.setMap(); this.showing = false;
  }
  this.polygon.setMap(map); // makes Polygon show when instantiated
}
var pp = new PointlessPolygon(map, coords);
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
  pp.showing ? pp.hide() : pp.show();
});

将.hide传递到googe.maps.event.addDomListener时,“this”关键字将绑定到窗口对象。您需要将“this”的实例保存到变量中,并从this.hide.Nope引用它。在对象中,这是指对象。实际上,在这些情况下,您对self的使用是毫无意义的,因为方法中的self引用了实例。现在,如果OP的其他代码没有弄糟的话,它可以工作了。但是,如果this.path要动态更改,您可能需要多边形中的this.path=path和path:self.path。您是对的。乍一看,我错误地推断这是指窗口实例。但这实际上是这个例子中的按钮对象,值得注意
function PointlessPolygon(map, coords){
  var t = this;
  this.map = map; this.coords = coords; this.showing = true;
  this.polygon = new google.maps.Polygon({paths:t.coords});
  this.show = function(){
    this.polygon.setMap(map); this.showing = true;
  };
  this.hide = function(){
    this.polygon.setMap(); this.showing = false;
  }
  this.polygon.setMap(map); // makes Polygon show when instantiated
}
var pp = new PointlessPolygon(map, coords);
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
  pp.showing ? pp.hide() : pp.show();
});