我想使用ES6创建对象工厂,但旧式语法不适用于新的.
我有下一个代码:
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');
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
我有一个 Node.js v11.11.0 应用程序。在此应用程序中,我的文件结构如下:
./src
/animals/
animal.js
tiger.js
koala.js
index.js
Run Code Online (Sandbox Code Playgroud)
如上所示,我在animals目录中定义了三个类。随着时间的推移,我打算添加更多具有更复杂逻辑的动物。此时,我的类定义如下:
动物.js
'use strict';
class Animal {
constructor(properties) {
properties = properties || {};
this.kind = 'Unknown';
}
eat(foods) {
for (let i=0; i<foods.length; i++) {
console.log(`Eating ${foods[i]}`);
}
}
}
module.exports = Animal;
Run Code Online (Sandbox Code Playgroud)
老虎.js
'use strict';
const Animal = require('./animal');
class Tiger extends Animal {
constructor(properties) {
super(properties);
this.kind = 'Tiger';
}
eat(foods) {
for (let i=0; i<foods.length; i++) {
if (foods[i].kind === 'meat') {
console.log(`Eating ${foods[i]}`); …Run Code Online (Sandbox Code Playgroud)