从基类执行重写的静态函数

时间:2019-01-31 19:43:55

标签: javascript class ecmascript-6 static extends

我想在不实例化的情况下从基类执行重写的静态方法。

我想在正在构建的应用程序上使用类似于MVC的模式,并且创建了一个名为Model的类,该类连接到数据库并获取对象,它具有一些我要覆盖的静态方法,例如表名(tableName)。问题在于必须从静态方法中调用此方法。

从基类开始,所有的工作都像一个咒语,问题是当我使用其他扩展基类的类时。

代码如下:

class Model {

    static get tableName() {
        return this.name;
    }

    static get primaryKey() {
        return "id";
    }

    static get columns() {
        return [];
    }

    static id(id) {
        return new Promise((resolve, reject) => {
            Model.get(Model.primaryKey, id)
            .then(models => {
                resolve(models[0]);
            });
        });
    }

    static get(columnName, value, compareSymbol) {
        return new Promise((resolve, reject) => {
            if (!compareSymbol) {
                compareSymbol = "=";
            }

            let sql = `select * from ${this.tableName}`,
            params = [];

            if (typeof columnName !== "undefined") {
                sql += ` where ${columnName} ${compareSymbol} ?`;
                params = [columnName, value];
            }

            console.log(sql, params);
        });
    }

    constructor(params) {
        this.target = new.target

        for (let name in params) {
            if (Model.primaryKey == name) {
                this[`#${name}`] = params[name];
            } else {
                this.set(name, params[name]);
            }
        }
    }

    set(name, value) {
        if (name != this.target.primaryKey && this.target.columns.indexOf(name) > -1) {
            this[`#${name}`] = value;
        }
    }

    get(name) {
        return this[`#${name}`];
    }

    executeSql(sql, variables) {
        console.log(sql, variables);
    }

    update() {
        let columns = this.target.columns.slice(),
        values = [],
        sql;

        sql = `update ${this.target.tableName} set ${columns.join("=?, ")}=? where ${this.target.primaryKey} = ${this.get(this.target.primaryKey)}`;

        for (let i = 0; i < columns.length; i++) {
            values.push(this.get(columns[i]));
        }

        return this.executeSql(sql, values);
    }
}

// from this line down is other different file

class Directory extends Model {
    static get tableName() {
        return "directories";
    }

    static get columns() {
        return [
            "name",
            "path",
            "recursive"
        ];
    }
}

// shows "from Model" expected "from directories"
Directory.id(2);

// work as expected
let d1 = new Directory({
    id: 1,
    name: "name",
    path: "path",
    recursive: false
});
d1.update();

如果在未实例化的情况下调用它,则会返回“ Model”,是否有任何方法可以从基类中获取重写的值?

0 个答案:

没有答案