【问题标题】:Proper way to initialize this attributes in JS object在 JS 对象中初始化此属性的正确方法
【发布时间】:2016-12-08 21:07:33
【问题描述】:

有什么办法可以制作这段代码:

function person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

看起来与此类似:

function person(first, last, age, eye) {
    this = {
        firstName: first,
        lastName: last,
        age: age,
        eyeColor: eye
    }
}

第一个方法要初始化很多变量,对于想要优化一切的程序员来说,这看起来很愚蠢。

【问题讨论】:

  • Object.assign(this,{ firstName: first, lastName: last, age: age, eyeColor: eye })
  • 第一种方法在我看来并不愚蠢。它简单易读。

标签: javascript class object optimization


【解决方案1】:

使用Object.assign()方法将对象属性复制到目标对象。

function person(first, last, age, eye) {
    Object.assign(this, {
        firstName: first,
        lastName: last,
        age: age,
        eyeColor: eye
    });
}

【讨论】:

    【解决方案2】:

    除了 Pranav 提到的 Object.assign() 之外。您也可以尝试将选项对象传递给构造函数。

    例如,

    function person(option) {
        this.option = option;
    }
    
    // usage
    var person1 = new person({
        firstName: first,
        lastName: last,
        age: age,
        eyeColor: eye
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 2016-01-12
      相关资源
      最近更新 更多