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

问题描述 投票:-1回答:1

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

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());
javascript debugging callback this
1个回答
2
投票
setTimeout(this.getNames.bind(this), 500)
                         ^
                         |
                         +----< HERE

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();
© www.soinside.com 2019 - 2024. All rights reserved.