【问题标题】:Create new class instance from existing class based on arry基于数组从现有类创建新类实例
【发布时间】:2021-02-02 22:01:12
【问题描述】:

这里是代码

class Test{
  contractor(name)
    this.name=name;
  getName() {
    return this.name;
  }
}

let myArry=['instance1','instance2,'instance3'];

我想要这样

let myArry[i] = new Test;
myArray[i].getName();

所以我有一个arry。想从 arry 自动生成新的类实例。

【问题讨论】:

  • 欢迎您!您的类定义不明确(例如,构造函数中缺少{})。查看ClassesmyArry 的第二个值未关闭(与')。您希望数组的元素i 成为类的实例,还是数组的所有元素?

标签: javascript class dynamic instance


【解决方案1】:

基本上你只需要在数组上调用Array.protype.map,作为你的回调函数,你使用箭头函数从数组值创建一个new Test

class Test {
  constructor(name) {
    this.name = name;
  }
  getName() {
    return this.name;
  }
}

const names = ['instance1','instance2','instance3'];
const instances = names.map( name => new Test(name) );

console.log( instances[1].getName() ); // logs 'instance2'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2013-09-04
    • 2011-11-02
    相关资源
    最近更新 更多