我有<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
对象,我需要纠正以使其以这种方式工作。
答案 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