JavaScript class is the blueprint for creating objects. It can be created using class
keyword followed by class name and then curly bracket {}
while Javascript objects can be created using class and a new keyword.
Source Code
class Person{
personInfo() {
document.write('I am a designer and developer' );
}
}
var obj = new Person();
obj. personInfo();
The javascript constructor method is used to create and initialize an object instance of that class.
In other words, the javascript constructor function creates an instance of a class that is known as an object
new keyword.
Source Code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
Code Explanation
The example above creates a class named "Person".
The class has two initial properties: "name" and "age".
A JavaScript class is not an object. It is the template or blueprint of an object that is used to create more than one object from the class i.e object blueprint.
Remember some of the important points:
this
keyword always refers to a newly created object and it becomes the current instance object.
Javascript objects can be created using class and with the help of a new
keyword.
Source Code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
let person1 = new Person("Smith", 25);
let person2 = new Person("John Doe", 30);
Class methods are similar to object methods. Let us see the general syntax for creating the class method.
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}
Source Code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
personInfo() {
document.write("I am static method");
}
}
var person1 = new Person("smith", 25);
person1.personInfo();
Code Explanation
this
keyword to call a static method within another static method.
this
keyword. To call a static method, you have to use the class name or as the property of the constructor like this.constructor.methodName().