如何在JavaScript对象中添加属性并赋值为同对象两属性拼接值
实现方案
下面提供几种在aboutMark对象内部新增拼接姓名属性的常用方式:
1. 使用Getter属性(推荐,支持动态更新)
通过定义getter属性,每次访问时自动拼接firstName和lastName,如果后续修改这两个属性,fullName会自动同步更新:
let aboutMark = { firstName: "Mark", lastName: "Miller", height: 1.69, weight: 78, // 新增getter属性 get fullName() { return `${this.firstName} ${this.lastName}`; }, bmiCalculator: function(){ this.markBMI = (this.weight / (this.height * this.height)) return this.markBMI } }; aboutMark.bmiCalculator(); console.log(aboutMark.fullName); // 输出 "Mark Miller" console.log(aboutMark);
2. 对象创建后手动添加静态属性
如果不需要动态更新姓名,可在对象初始化完成后直接添加属性:
let aboutMark = { firstName: "Mark", lastName: "Miller", height: 1.69, weight: 78, bmiCalculator: function(){ this.markBMI = (this.weight / (this.height * this.height)) return this.markBMI } }; // 新增拼接属性 aboutMark.fullName = `${aboutMark.firstName} ${aboutMark.lastName}`; aboutMark.bmiCalculator(); console.log(aboutMark.fullName); // 输出 "Mark Miller" console.log(aboutMark);
3. 初始化时直接定义静态属性
若姓名不会变更,也可以在对象字面量中直接定义拼接后的属性,需要提前提取姓名变量:
const firstName = "Mark"; const lastName = "Miller"; let aboutMark = { firstName, lastName, fullName: `${firstName} ${lastName}`, height: 1.69, weight: 78, bmiCalculator: function(){ this.markBMI = (this.weight / (this.height * this.height)) return this.markBMI } }; aboutMark.bmiCalculator(); console.log(aboutMark.fullName); // 输出 "Mark Miller" console.log(aboutMark);
内容的提问来源于stack exchange,提问作者kapil choudhary
相关产品推荐
相关产品推荐

