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.
Atas ialah kandungan terperinci Bagaimana untuk Mencipta Objek dari Nama Kelas dalam ES6?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!