ホームページ > 記事 > ウェブフロントエンド > ES6 でクラス名からオブジェクトを作成するには?
Creating Objects from Class Names in JavaScript ES6
When attempting to create an object factory in ES6 using the traditional old-style syntax, you may encounter an error. This is because the old syntax is incompatible with the new ES6 syntax.
In the provided code snippet:
export class Column {} export class Sequence {} export class Checkbox {} export class ColumnFactory { constructor() { this.specColumn = { __default: 'Column', __sequence: 'Sequence', __checkbox: 'Checkbox' }; } create(name) { let className = this.specColumn[name] ? this.specColumn[name] : this.specColumn['__default']; return new window[className](name); // this line throw error } } let factory = new ColumnFactory(); let column = factory.create('userName');
The error occurs in the line return new window[className](name); because it attempts to access the class name as a global variable. This approach fails in ES6, as classes are not exposed as global variables.
Solution:
To resolve this issue, replace the class names in the specColumn object with the actual class references:
export class Column {} export class Sequence {} export class Checkbox {} export const columnFactory = { specColumn: { __default: Column, // <-- __sequence: Sequence, // <-- __checkbox: Checkbox // <-- }, create(name, ...args) { let cls = this.specColumn[name] || this.specColumn.__default; return new cls(...args); } };
By doing so, you no longer rely on class names being available globally and can access classes directly from the specColumn object.
以上がES6 でクラス名からオブジェクトを作成するには?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。