javascript:如何在不使用new关键字的情况下从类创建新实例

时间:2017-05-05 18:09:52

标签: class ecmascript-6

我想使用类创建ES6的简单插件。但不使用新关键字。可以自动从类中返回新实例。

示例:

class Rectangle{
    constructor(x, y){
        this.x = x,
        this.y = y
    }

    eq(){
        console.log('Result ' + this.x * this.y )
    }

}

const myRect = new Rectangle(10, 10);
myRect.eq();

我想像这样使用

Rectangle.eq(10, 10);

3 个答案:

答案 0 :(得分:1)

您可以使用模块设计模式。

var Rectangle = (function() {
  return {
    eq: function(x, y) {
      console.log(x * y);
    }
  };
})();

Rectangle.eq(2,5); 

点击此处查看:https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know

答案 1 :(得分:0)

Reflect.construct做同样的事情:

class Rectangle{
    constructor(x, y){
        this.x = x,
        this.y = y
    }

    eq(){
        console.log('Result ' + this.x * this.y )
    }

}

Reflect.construct(Rectangle, [10, 10]).eq();

答案 2 :(得分:0)

eq()定义为static method。那么你不必实例化你的课程,但可以直接使用它。