ES2015 - 使用静态方法在每次调用时新建一个构造函数有什么缺点?

时间:2016-05-26 07:29:07

标签: javascript node.js class static ecmascript-6

我正在为knex.js编写一个简单的ORM /包装器,我试图在两种方法之间做出决定。

第一种方法只是一个必须在使用前实例化的常规类:

class Base {

    constructor() {
        this.db = db;
    }

    all() {
        return this.db(this.table);
    }

    find(id) {
        return this.db(this.table).where('id', id).first();
    }

    // more similar methods...

}

class User extends Base {

    constructor() {
        super();
        this.table = 'users';
    }

}

// calling code
let user = new User();
user.find(1).then(user => console.log(user));

我更倾向于使用的第二种方法使用创建实例的静态方法:

class Base {

    constructor() {
        this.db = db;
    }

    static all() {
        const model = new this;
        return model.db(model.table);
    }

    static find(id) {
        const model = new this;
        return model.db(model.table).where('id', id).first();
    }

}

// calling code
User.find(1).then(user => console.log(user));

我喜欢静态方法,因为API更干净(无需实例化),但我不熟悉缺点。所以我的问题是这是一个好方法吗?如果没有,为什么?是否有第三种选择位于中间哪个更好?

1 个答案:

答案 0 :(得分:0)

如果你想避开物体怎么样?

class Base {
  constructor() {  }
  static all() {
    return db(this.table())
  }
  static find(id) {
    return db(this.table()).where('id', id).first()
  }
}

class User extends Base{
  constructor() {
    super()
  }
  static table(){
    return 'users'
  }  
}

// calling code
User.find(1).then(user => console.log(user));

这样可行,但我不知道这是做事的好方法,对于初学者来说,Base.all()会抛出错误,如果所有的类方法都是静态的,你不妨使用普通的js对象如:

let Base = {
    all: function(){ 
      return db(this.table)
    },
    find: function(id){
      return db(this.table.where('id', id).first()
    }
  }
  , extend = (a,b) => {for(let i in b) a[i] = b[i]}
  , User  = {table: 'users'}

// calling code
User.find(1).then(user => console.log(user));
相关问题