0

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)

6
  • A static method is nothing more than a class method. If you don't intend on having class instances using that method then you have nothing to feel weird about. Commented Dec 7, 2016 at 19:37
  • What exactly are you trying to achieve? Why not just make it a normal non-static method? Commented Dec 7, 2016 at 19:38
  • Static methods are not subject of inheritance. What you do seems fine. What is the issue? Commented Dec 7, 2016 at 19:39
  • @Timo can't use it as a non-static method because I want to ensure the good practice of class methods to use this. Commented Dec 7, 2016 at 19:45
  • @trincot I know both are correct but I'm not sure, in a performance/readbility/good practice is the best way to implement (although I don't have to restrict myself to just one way of doing this) Commented Dec 7, 2016 at 19:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How come I can do C.testMethod2() but not this.testMethod() ? I think this just shows I need to grab a book...
Static methods are methods of the class (A, C) itself, not of the instances (new A, new C). If this refers to an instance, you only can access the properties that it inherits from the prototype objects (A.prototype, C.prototype).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.