【问题标题】:How to add an array property in an object constructor?如何在对象构造函数中添加数组属性?
【发布时间】:2021-04-26 12:50:26
【问题描述】:
const myCountry = function (country, capital, language, population) {

     (this.country = country),

     (this.capital = capital),

     (this.language = language),

     (this.population = population),
 
     (this.neighbours = []);
   
};

const Utopia = new myCountry("Utopia", "rabat", "arabic", "18 million", [
  "algeria",
  "tunisia",
]);

【问题讨论】:

  • 在构造函数中添加optional neighbours parameter,例如function MyCountry(country, capital, language, population, neighbours = [])并使用this.neighbours = neighbours
  • 谢谢!可以,忘记参数了

标签: javascript object constructor


【解决方案1】:

使用spread syntax

class myCountry {
  constructor(country, capital, language, population, neighbours) {
    this.country    = country
    this.capital    = capital
    this.language   = language
    this.population = population
    this.neighbours = [...neighbours]
  }
}

const Utopia = new myCountry('Utopia', 'rabat', 'arabic', '18 million', ['algeria','tunisia'])


console.log( Utopia.neighbours )

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2014-09-18
    • 2019-04-20
    • 2014-04-22
    • 2018-06-11
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多