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.
There are some properties and methods that only belong to class. For example: counting the number of objects created by the class
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
- Static keyword for static methods like class methods.
Static method
can be called with creating a single instance of object.- Do not use the instance properties in class methods.
- 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>