我正在尝试完成一个函数,该函数接收一个对象作为参数,并返回一个基于接收到的描述性对象生成的类(或构造函数)。不使用“eval”有什么解决办法吗?
// this is the function to create class.
function createClass (option) {
// TODO how to generate...
// return classGenerated
}
// then, i can do this to create a 'Node' class.
createClass({
name: "Node",
data: {
x: 0,
y: 0
},
methods: {
translate (dx, dy) {
this.x += dx;
this.y += dy;
}
}
})
// then i can create a instance by doing this below.
const node = new Node();
我已经通过“eval”函数完成了一个版本。我想知道是否还有其他更好的方法可以做到这一点。感谢您的帮助。
最佳答案
考虑使用类对象,而不是独立的动态变量名,并按类名索引(例如 Node
),以便您可以执行类似 const node = newcreatedClasses 的操作.Node()
:
const createdClasses = {};
function createClass ({ name, data, methods }) {
class theClass {
constructor() {
Object.assign(this, data);
}
}
Object.assign(theClass.prototype, methods);
createdClasses[name] = theClass;
}
createClass({
name: "Node",
data: {
x: 0,
y: 0
},
methods: {
translate (dx, dy) {
this.x += dx;
this.y += dy;
}
}
})
const node = new createdClasses.Node();
node.translate(5, 5);
console.log(node.x);
关于javascript - 如何从描述性对象动态生成类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54165322/