Call static methods from regular ES6 class methods

前端 未结 3 749
说谎
说谎 2020-11-22 15:14

What\'s the standard way to call static methods? I can think of using constructor or using the name of the class itself, I don\'t like the latter since it doesn

3条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 15:48

    If you are planning on doing any kind of inheritance, then I would recommend this.constructor. This simple example should illustrate why:

    class ConstructorSuper {
      constructor(n){
        this.n = n;
      }
    
      static print(n){
        console.log(this.name, n);
      }
    
      callPrint(){
        this.constructor.print(this.n);
      }
    }
    
    class ConstructorSub extends ConstructorSuper {
      constructor(n){
        this.n = n;
      }
    }
    
    let test1 = new ConstructorSuper("Hello ConstructorSuper!");
    console.log(test1.callPrint());
    
    let test2 = new ConstructorSub("Hello ConstructorSub!");
    console.log(test2.callPrint());
    
    • test1.callPrint() will log ConstructorSuper Hello ConstructorSuper! to the console
    • test2.callPrint() will log ConstructorSub Hello ConstructorSub! to the console

    The named class will not deal with inheritance nicely unless you explicitly redefine every function that makes a reference to the named Class. Here is an example:

    class NamedSuper {
      constructor(n){
        this.n = n;
      }
    
      static print(n){
        console.log(NamedSuper.name, n);
      }
    
      callPrint(){
        NamedSuper.print(this.n);
      }
    }
    
    class NamedSub extends NamedSuper {
      constructor(n){
        this.n = n;
      }
    }
    
    let test3 = new NamedSuper("Hello NamedSuper!");
    console.log(test3.callPrint());
    
    let test4 = new NamedSub("Hello NamedSub!");
    console.log(test4.callPrint());
    
    • test3.callPrint() will log NamedSuper Hello NamedSuper! to the console
    • test4.callPrint() will log NamedSuper Hello NamedSub! to the console

    See all the above running in Babel REPL.

    You can see from this that test4 still thinks it's in the super class; in this example it might not seem like a huge deal, but if you are trying to reference member functions that have been overridden or new member variables, you'll find yourself in trouble.

提交回复
热议问题