在javascript es6中,如何在不使用类名的情况下调用构造函数方法?

时间:2017-07-14 19:36:07

标签: javascript inheritance polymorphism es6-class

我试图创建一个可以处理基本CRUD函数的父类,但我无法弄清楚如何在静态方法中调用构造函数。

class Model {
  static find(id) {
    var attrs = someDBcalls();
    var obj = new CurrentClass(attrs);   // how?
    return obj;
  }
}

class User extends Model {
  constructor(attrs){
    // initialize class.
  }
}

User.find(1);  // shall return an User object.

1 个答案:

答案 0 :(得分:1)

您可以使用var obj = new this(attrs);,如下所示:



function someDBcalls(id) {
  return { id, success: true };
}

class Model {
  static find(id) {
    var attrs = someDBcalls(id);
    var obj = new this(attrs);
    return obj;
  }
}

class User extends Model {
  constructor(attrs) {
    super();
    // initialize class.
    console.log(attrs);
  }
}

var user = User.find(1);  // shall return an User object.
console.log(user instanceof User);