简体   繁体   中英

ES6 React - static method vs constructor

I'm running into an "issue" where I don't know which one is the best option.

Say I have the following class

export default class A {
   constructor(){
       this.testMethod = function testMethod(){
           console.log('a')
       }
   }

   static testMethod2 = function() {
       console.log('B')
   }
}

now I'm extending this class

class C extends A {
    fetch() {
        this.testMethod()
        A.testMethod2()      
    }            
}

Defining it as a static method feels weird to use when extending it, I would assume the fact that I'm extending a class would allow me to access all of its own methods (ES5 prototype style)

I know both ways are correct but what's the best way to do this in ES6/React ? What are some caveats of both ways or performance issues ?

I'm currently using the constructor because it feels like the right/intended way of doing it but I can't "justify" one over the other.

All this came from applying the airbnb eslint to my code base ( http://eslint.org/docs/rules/class-methods-use-this )

I would assume the fact that I'm extending a class would allow me to access all of its own methods

You actually can do that. Just call C.testMethod2() instead of A.testMethod2() (or even use this.constructor.testMethod2() ).

Defining functions that have nothing to do with a particular instance on the prototype or even inside the constructor is a bad practise, don't do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM