首页 > 解决方案 > 对象字面量中的全名

问题描述

我正在尝试使用对象文字中的函数来获取全名,但失败了。我使用的代码如下所示。我可能做错了什么?

fullName function(){ 
return this.firstName +" "+this.lastName;
} 
console.log(person.fullName());

标签: javascriptobject

解决方案


如果你想使用 fullName() 作为 person 对象的方法,你首先需要一个 person 对象。

const person = { 
  firstname: "john",
  lastname: "doe",
  fullName() {
    return `${this.firstname} ${this.lastname}`
  }
}

console.log(person.fullName());


推荐阅读