函数调用对象有延迟

时间:2018-02-28 08:40:48

标签: javascript

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

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:无法读取未定义的属性'map'

我尝试过做

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

我刚刚回到我身边。

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

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



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




答案 1 :(得分:1)

或者,使用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);




答案 2 :(得分: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);