Class Methods in JavaScript Tutorial

In this section, we will learn what the Class Methods are and how to use them in JavaScript.

Note: we’re assuming you’re already familiar with the JavaScript class.

What is Class Method in JavaScript?

In the body of a class, we can define methods. These methods are shared between objects that are created from that class.

Basically, the methods in the body of a class (excluding the construct method) are shared between objects and not copied for each object!

Let’s see an example:

class Person{
        constructor (firstName, lastName){
          this.lastName = firstName; 
          this.firstName = lastName;
        }
        getName(){
          return this.firstName;
        }
        setName(name){
          this.firstName = name;
        }
        getLastName(){
          return this.lastName;
        }
        setLastName(lastName){
          this.lastName = lastName;
        }
}

Notes:

  • Methods in a class don’t need to be separated from each other via the comma `,`.
  • The rules for the `this` keyword are the same in the class methods.

Here we have 4 methods and each object that is created from this class will have the access to it.

If you remembered from the prototype section, we mentioned that any property that is set in the prototype-object of a constructor function is shared between the objects of that constructor-function.

The same is true for methods in the classes as well.

Example: creating JavaScript class method

class Person{
  constructor (firstName, lastName){
    this.lastName = firstName; 
    this.firstName = lastName;
  }
  getName(){
    return this.firstName;
  }
  setName(name){
    this.firstName = name;
  }
  getLastName(){
    return this.lastName;
  }
  setLastName(lastName){
    this.lastName = lastName;
  }
}

const prs1 = new Person("John","Doe");
const prs2 = new Person("Omid","Dehghan");

prs1.__proto__.getLastName = function(){return"Good Bye";}
console.log(prs1.getLastName());
console.log(prs2.getLastName());

Output:

Good Bye

Good Bye

Did you see what happened?

Note: if you’re not familiar with the dunder proto (__proto__), please read the `prototype` section, where we explained the dunder proto as well.

Here, via the dunder proto and the `prs1` object, we’ve accessed the `getLastName` identifier and changed its functionality! After that, when calling the same method via the `prs2` we can see this change appeared for this object as well.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies