invoke method inside class javascript

hljs.highlightAll();

Invoke Method Inside Class JavaScript

When working with classes in JavaScript, you might need to invoke a method inside the same class. There are different ways to do this, and we will explore some of them.

Using the 'this' keyword

The 'this' keyword refers to the current object, which in this case is the class instance. You can use it to call methods inside the class.


class MyClass {
  myMethod() {
    console.log('Hello from myMethod');
  }
  
  myOtherMethod() {
    this.myMethod();
  }
}

const myClass = new MyClass();
myClass.myOtherMethod(); // Output: "Hello from myMethod"
    

Using the class name

You can also use the class name to call a method inside the class. This is useful when you need to call a static method.


class MyClass {
  static myStaticMethod() {
    console.log('Hello from myStaticMethod');
  }
  
  myOtherMethod() {
    MyClass.myStaticMethod();
  }
}

MyClass.myStaticMethod(); // Output: "Hello from myStaticMethod"

const myClass = new MyClass();
myClass.myOtherMethod(); // Output: "Hello from myStaticMethod"
    

Using the super keyword

The 'super' keyword is used to call a method from a parent class. This is useful when you have a subclass that overrides a method from the parent class but still needs to call the parent method.


class ParentClass {
  myMethod() {
    console.log('Hello from ParentClass');
  }
}

class ChildClass extends ParentClass {
  myMethod() {
    super.myMethod();
    console.log('Hello from ChildClass');
  }
}

const childClass = new ChildClass();
childClass.myMethod(); // Output: "Hello from ParentClass" "Hello from ChildClass"
    

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe