我可以在ES6中的父类的静态方法中使用类变量吗? [英] Can I use class variables in the parent class's static methods in ES6?

查看:51
本文介绍了我可以在ES6中的父类的静态方法中使用类变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是奇怪的或反模式的。

Sorry if this is bizarre or anti-pattern.

假设我在子类上有一个静态方法,例如(为了便于阅读而大大简化)

Suppose I have a static method on a child class, e.g (heavily simplified for readability)

class User extends Model {
  //...
    static getAll(){
      db.execute('SELECT * FROM users');
    }
}

由于我有多个型号,我可能需要 getAll 方法打开,似乎理想的是在模型上定义 getAll class,它引用 tableName 类变量。理想情况下它看起来像

Since I have multiple models I might want a getAll method on, it seems ideal to define getAll on the Model class, which makes reference to a tableName class variable. Ideally it would look something like

class Model {
  static getAll(){
    db.execute(`SELECT * FROM ${this.tableName}`);
  }
}
//...
User.tableName = 'users';

这不起作用,因为ES6不喜欢你这样定义类变量。 有许多变通办法,例如添加 tableName 参数然后在用户中将用户应用于<* c $ c>:

This won't work, because ES6 doesn't like you defining class variables like that. There are a number of workarounds, such as adding a tableName parameter in the parent then applying users to it in User:

class Model {
  static getAll(tableName) {
    db.execute(`SELECT * FROM ${tableName}`)
  }
}
//...
class User extends Model{
  static getAll() {
    Model.getAll('users')
  }
}

但显式重写所有类的子项的继承函数这似乎是可怕的反模式。我见过的其他解决方案(例如使用静态函数返回常量,或者将两个类包装在对象中)都有点难看,而不是我想要提交的模式,除非我必须这样做。所以我正在寻找一个易于阅读的ES6模式,它允许我执行以下操作:

but explicitly re-writing inherited functions for all of a class's children like this seems dreadfully anti-pattern. Other solutions I've seen (such as using static functions to return constants, or wrapping both classes in an object) are kinda ugly and not a pattern I want to commit to unless I have to. So I'm looking for an easily-readable ES6 pattern that lets me do the following:


  1. 从父类继承静态方法。

  2. 引用父类中的类变量(或类似的东西),以便可以为不同的子类指定它们

  3. 不必显式引用继承子类中的方法。

这样的解决方案是否存在,或者是否值得在ES5中采用硬方式 ?

Does such a solution exist, or is it worth doing it the 'hard way' in ES5?

推荐答案


这不起作用,因为ES6不喜欢你定义类变量那个。

This won't work, because ES6 doesn't like you defining class variables like that.

是什么让你这么想的? 用户是一个类似于任何其他功能的功能。静态方法成为该函数的属性。直接将属性分配给用户就可以了。

What makes you think that? User is a function like any other function. Static methods become properties of that function. Assigning a property directly to User works just fine.

class Model {
  static getAll() {
    return `SELECT * FROM ${this.tableName}`;
  }
}

class User extends Model {}
User.tableName = 'users';
class Product extends Model {}
Product.tableName = 'product';


console.log(User.getAll());
console.log(Product.getAll());

这篇关于我可以在ES6中的父类的静态方法中使用类变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆