假设我在字符串中定义了类,如下所示:
`class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}`
是否可以将字符串转换为javascript类,以便运行以下命令?或类似..
const square = new Rectangle(10, 10);
console.log(square.area);
答案 0 :(得分:2)
看起来像是这样的副本:Using eval method to get class from string in Firefox
不要忘记将课程放在括号之间。
var class_str = `(class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
})`;
var a = eval(class_str);
console.log(new a(10, 10));
答案 1 :(得分:1)
如果将字符串传递给eval
,可以将字符串转换为类,如下所示:
eval("function MyClass(params) {/*Some code*/}");
var foo = new MyClass({a: 1, b: 2});
编辑:
根据评论我发现问题中显示的语法没问题,但它似乎与eval
不兼容。但是,做了一些实验,我发现了以下技巧:
eval("window['Rectangle'] = class Rectangle {constructor(height, width) {this.height = height;this.width = width;}get area() {return this.calcArea();}calcArea() {return this.height * this.width;}}");
var r = new Rectangle(50, 40);