Skip to content
the poor coder

invoke method inside class javascript

Poor Man
Published
Reading time
1 min read
On this page

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.

Text

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.

Text

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.

Text

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"
    

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC