javascript,绑定(bind) `this` 不起作用

标签 javascript

我有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/

相关文章:

javascript - SVG,当我动态创建文本时,文本不会在 textPath 上呈现

javascript - Vue Tables 2自定义过滤器不起作用

javascript - 什么是导出对象?

php - 单击元素时切换 CSS 样式

javascript - 应用程序Phonegap内的Json!什么是路径?

javascript - 表单未得到验证

javascript - 解析 Facebook 登录在 ionic View 中不起作用

javascript - 仅当我按 F12 调出控制台时,表单才能在 Internet Explorer 中工作

javascript - 模态不会在 native react 中打开。给出 "undefined is not an object"错误

javascript - 为简单的 Firebase 聊天添加时间