Class methods and properties
What is method in class? Static methods in class Properties with initial values constructor() method
What is method in class?
Methods are defined on the prototype of each class instance and shared by all instances. Class methods are functions that belong to a class and can be called on instances of that class.
We always add a constructor() method before adding any number of methods.
Syntax
class className{
constructor(){.....}
method1 () {.....}
method2 () {....}
}
Example
class Person{
constructor(name) {
this.name=name;
}
showName( ) {
console.log("Hello, my name is",this.name);
}
}
const person1=new Person("rahul");
person1.showName( );
Class methods can access properties of the class instances through the 'this' keyword.
Static methods in class
Static class methods are defined on the class itself. Static methods can be called without an instance of the class. They are typically used to implement utility functions that operate on class-level data.
Example
class Myclass {
static staticMethod( ) {
console.log(" This is static method trial");
}
}
Myclass.staticMethod( );
It is called by class name followed by method name.
Properties with initial values
When we make a class object, it may be chances that some properties may have an initial value. For example, if we make a class of beginner programmer, then the level of the programmer would be 0 and skills would be empty.
class Beginner{
constructor(fname,lname,age,city) {
this.fname=fname;
this.lname=lname;
this.age=age;
this.city=city;
this.level=0;
this.skills=[ ];
}
getfullname ( ) {
const fullname =this.fname + this.lname;
return fullname;
}
}
const person1=new Beginner('anuska', 'kumari', 33, 'Gonda');
console.log(person1.level); //accessing level property
console.log(person1.skills); //access skills property