Javascript从字符串创建类对象

时间:2017-08-17 10:33:17

标签: javascript

假设我在字符串中定义了类,如下所示:

`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);

2 个答案:

答案 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));

这里的工作演示:http://jsbin.com/netipuluki/edit?js,console

答案 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);