我有map
对象,在属性markersLocation
中我绑定(bind)了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不是一个函数
我想使用 this
作为 map
对象,我需要纠正它才能以这种方式工作。
最佳答案
您在声明 map
对象时绑定(bind) this
的值。
就运行时而言,在完成对象字面量的计算之前,不存在 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({})
, this 的值就不会有任何歧义。
关于javascript,绑定(bind) `this` 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36077727/