javascript,绑定`this`不行

时间:2016-03-18 06:38:10

标签: javascript

我有<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> <version>1.3.3.RELEASE</version> </dependency 个对象,在属性map我绑定markersLocation所以我可以在函数内使用它但是this是其他的

this

我得到了这个(function(){ var map = { ... init: function(options){ ... this.markersLocation(); ... }, // markers placeMarker: function(distrybutors, instalators){ for (var i = 0; i < distrybutors.length; i++) { var LatLng = this.getGeoAddress(distrybutors[i].address); var marker = new google.maps.Marker({ map: this.mapObj, position: LatLng }); } }.bind(this), markersLocation: function() { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200){ var jsonData = JSON.parse(xmlHttp.responseText); if (jsonData.status) { console.log(this); this.placeMarker(jsonData.distrybutors, jsonData.instalators); } else { console.log('error'); } console.log(jsonData.instalators); } }.bind(this) xmlHttp.open("GET", document.querySelector('#urlAdress').value, true); // true for asynchronous xmlHttp.send(); }.bind(this), } map.init({ location: "50.1943227,17.8434933" }); })(); 我想使用TypeError: this.placeMarker is not a function作为this对象,我需要纠正以使其以这种方式工作。

2 个答案:

答案 0 :(得分:1)

您在声明this对象时绑定map的值。

就运行时而言,在完成对象文字的评估之前,没有map个对象。因此this会引用window

如果您删除顶级方法的.bind(this)次调用,则应该有效。

placeMarker: function(distrybutors, instalators){
  for (var i = 0; i < distrybutors.length; i++) {
    var LatLng = this.getGeoAddress(distrybutors[i].address);

    var marker = new google.maps.Marker({
    map: this.mapObj,
      position: LatLng
    });

  }
}.bind(this),  // `this` is not what you think it is

看到你已经在IIFE中评估过这个问题,你可能想要全力以赴并将其重写为一个类。

function Map() {
  this.init = function() { };

  this.placeMarker = function() {

  }.bind(this);

  // ...
}

这种方式(只要您使用new Map()Map.call({}),就不会有关于此值的歧义。

答案 1 :(得分:0)

当它被称为时应该存在:

groupby

您可以从那里关注更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind