【问题标题】:Javascript [How to concatenate] [duplicate]Javascript [如何连接] [重复]
【发布时间】:2022-01-06 12:47:55
【问题描述】:

const mark = {
    firstName: `Mark`,
    lastName: `Miller`,
    fullName: this.firstName + this.lastName,
    weight: 78,
    height: 1.69
};

console.log(mark.fullName); // the result in console: NaN

【问题讨论】:

  • this 指的是对象(窗口)的容器,而不是对象本身。如果要创建范围,请使用函数,或者更好的是使用类。 window.firstName 是未定义的,在 Javascript 中,undefined + undefined 给出......“不是一个数字”NaN 因为它试图将东西加在一起,它假设它应该在结束。

标签: javascript object


【解决方案1】:
const mark = {
    firstName: `Mark`,
    lastName: `Miller`,
    fullName: function(){
                           return this.firstName + this.lastName;
                       },
    weight: 78,
     height: 1.69
};
console.log(mark.fullName());

Alternate:

const mark = ({
    firstName: `Mark`,
    lastName: `Miller`,
    init: function(){
                this.fullName = this.firstName + this.lastName;
            },
    weight: 78,
    height: 1.69
}).init();
console.log(mark.fullName);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2019-01-16
    • 1970-01-01
    • 2014-09-16
    • 2021-02-05
    • 1970-01-01
    相关资源
    最近更新 更多