(javascript)这段代码似乎有两个问题

时间:2018-03-05 17:15:50

标签: javascript debugging callback this

我是否需要在某处执行bind(this)并且控制台日志位置似乎已关闭?

var company = {
  employees: [{
      name: "doug"
    },
    {
      name: "AJ"
    }
  ],
  getName: function(employee) {
    return employee.name
  },
  getNames: function() {
    return this.employees.map(this.getName)
  },
  delayedGetNames: function() {
    setTimeout(this.getNames, 500)
  }
}

console.log(company.delayedGetNames());

1 个答案:

答案 0 :(得分:2)

setTimeout(this.getNames.bind(this), 500)
                         ^
                         |
                         +----< HERE

&#13;
&#13;
var company = {
  employees: [{
      name: "doug"
    },
    {
      name: "AJ"
    }
  ],
  getName: function(employee) {
    return employee.name
  },
  getNames: function() {
    return this.employees.map(this.getName)
  },
  delayedGetNames: function() {
    var fn = function() {
      var names = this.getNames();
      console.log(names);
    };
    
    setTimeout(fn.bind(this), 500);
  }
}

company.delayedGetNames();
&#13;
&#13;
&#13;