【问题标题】:function call on object with delay延迟对对象的函数调用
【发布时间】:2018-08-08 01:51:46
【问题描述】:

我正在尝试让此代码返回每个员工的姓名。

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());

但是,当我运行代码时,我得到“TypeError: Cannot read property 'map' of undefined”

我试过了

setTimeout(this.getNames.bind(this),500)

我只是得到未定义的返回给我。

谁能帮帮我?

【问题讨论】:

标签: javascript


【解决方案1】:

用很少的技巧和getters

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

console.log(company.delayedGetNames);

【讨论】:

    【解决方案2】:

    您需要向函数添加回调才能获取名称。

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

    【讨论】:

      【解决方案3】:

      或者,使用Promise,你可以这样写:

      var company = {
          employees: [
              {
                  name: "doug"
              },
              {
                  name: "AJ"
              }
          ],
          getName: function(employee){
              return employee.name
          },
          getNames: function(){
              return this.employees.map(this.getName)
          },
          delayedGetNames: function() {
              return new Promise(resolve => setTimeout(() => resolve(this.getNames()), 1000));
          }
      }
      
      company.delayedGetNames().then(console.log);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-07
        • 1970-01-01
        相关资源
        最近更新 更多