JavaScript Class Methods and Class Properties

In this section, you will learn about class methods and class properties of JavaScript. Usually, the properties and methods are for objects, however, JavaScript has properties and methods for class also.

Advertisements

There are some properties and methods that only belong to class. For example: counting the number of objects created by the class

Advertisements
   constructor(name, subject) {
       this.name = name;
      this.subject = subject;
      Student.count++;  // class property 
}
static add(a, b){         //class method uses static keyword
     const answer = a  + b;     //using const keyword to declare a const variable that never changes.
}
}
Student.count = 0; //declaring class property outside of class
//create some objects 
let  peter = new Student(“Peter Parker”, “Mathematics”);
let  John = new Student(“John Rambo”, “Computers”);
console.log(Student.count);     //prints 2 
console.log(Student.add(30,44)); //prints 74 

Rules for Class Properties and Class Methods

  1. Static keyword for static methods like class methods.
  2. Static method can be called with creating a single instance of object.
  3. Do not use the instance properties in class methods.
  4. Static methods are usually created for utility functions for an application – source Mozilla Developer Network

Example Program for Class Method and Class Properties

<!DOCTYPE html>
<html>
<body>
<script>
class Person {
    constructor(firstName, lastName) {
        this.firstName = firstName; // "normal name"
        this._lastName = lastName; // starts with "_"
    }

    get lastName() {
        return this._lastName.toUpperCase();
    }
    set lastName(newName) {
        // validation could be checked here such as 
        // only allowing non numerical values
        this._lastName = newName; 
    }
    walk() {
        return (this.firstName + ' ' + this._lastName + ' is walking.');
    }
}
let p1 = new Person('Peter', 'Parker');
document.body.innerHTML += p1.lastName;
</script>
</body>
</html>

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.