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 중국어 웹사이트의 기타 관련 기사를 참조하세요!