代码之家  ›  专栏  ›  技术社区  ›  Hirurg103 Tilendor

是否可以从基类[node JS]中的静态方法实例化子类[[副本]

  •  0
  • Hirurg103 Tilendor  · 技术社区  · 6 年前

    我想从基类中的静态方法创建子类的实例

    class Base {
      static find(id) {
        const attributes = database.get(id);
        return new getChildClass(attributes);
      }
    }
    
    class FirstChild extends Base {
    }
    
    class SecondChild extends Base {
    }
    

    我想要 FirstChild.find(1) 返回的实例 FirstChild SecondChild.find(1) 返回的实例 SecondChild

    在节点JS中是否可以实现这一点?

    1 回复  |  直到 6 年前
        1
  •  2
  •   CertainPerformance    6 年前

    打电话的时候 find this 里面 将引用那个子类,所以您可以 return new this

    class Base {
      static find(id) {
        const attributes = 'foo'; // database.get(id);
        return new this(attributes);
      }
    }
    
    class FirstChild extends Base {
    }
    
    class SecondChild extends Base {
    }
    
    console.log(FirstChild.find(1) instanceof FirstChild);
    console.log(SecondChild.find(1) instanceof SecondChild);