【问题标题】:Javascript class from string variable name [duplicate]来自字符串变量名的Javascript类[重复]
【发布时间】:2021-08-26 10:26:19
【问题描述】:

我有一个类名,想用它来动态创建一个类实例。我该怎么做?

class FieldText {
  constructor() {
    console.log('hello text field');
  }
}

class FieldTextarea {
  constructor() {
    console.log('hello textarea field');
  }
}

function callField(name) {
  new FieldText(); // Somehow use name variable instead to make it dynamic
  // new Field${name}(); // Does not work
}

callField('text');

【问题讨论】:

  • 将类放在一个对象中并引用它? globalThis.FieldTextarea = FieldTextarea 允许 globalThis['FieldTextarea']
  • const elements = { Text: fieldText; Textarea: FieldTextarea }; 然后你可以做new elements[name]

标签: javascript class dynamic


【解决方案1】:

class FieldText {
  constructor() {
    console.log('hello text field');
  }
}

class FieldTextarea {
  constructor() {
    console.log('hello textarea field');
  }
}

this.FieldText = FieldText;
this.FieldTextarea = FieldTextarea;

function callField(name) {
  return new this[`Field${name}`];
}

callField('Text');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-29
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2020-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多