Es6箭头功能'这个'在一个对象

时间:2018-01-06 09:29:04

标签: javascript ecmascript-6 this arrow-functions

我有以下代码,我循环遍历一个对象并显示其属性值,或者如果它是一个函数则调用该值。

 let person = {
  fname: "Joseph",
  lname: "Michuki",
  age: 22,
  profession: "developer",
  address: "10105550-81 Othaya",
  fullname: () => this.fname + " " + this.lname
};

for(i in person){
    if(typeof person[i] === 'function'){
        console.log(person[i]()); // this logs undefined since the value of this defaults to window which has no fname or lname variables
        console.log(person.i); //this results in a type error since i is a string and not a function
        console.log(person[i].call(person)); //this logs undefined undefined since the 'this' passed is ignored
    }else {
        console.log(person[i]);
    }
}

我的问题是,我如何参考'姓名'循环中person对象的功能,以便记录正确的值? 谢谢。

0 个答案:

没有答案