Well first of all you have to acknowledge that JavaScript is the weirdest language ever on earth And most crazy as well And most beautiful at the same time. so OOP in javascript is not the same as another language like C++/Java. in ES6 we got class
keywords. class syntax in javascript it's just a wrapper over function. a class may have only one constructor
. so we can't use multiple constructors.
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
}
let processor = new Product("Intel core i-9", 65000);
let monitor = new Product("LG w49", 35000);
console.log(processor, monitor);
The code above does the following:
We created a class Product with two parameters: name and price. Creates 2 objects of the class. Creates a constructor function for a product object. Accepts two arguments, name, and price, and assigns them to the object properties. Creates a new object and sets the properties name and price to the values passed in. Returns the newly created object.
this
keyword in javascript is different from java(whenever you create an object, it has a property this
and this
points to the same object)/c++/c# this
.
in javascript, this
keyword refers to the calling site (from where the function or class is called).
whenever you have to access a data member inside a member function we need to access it using this
keyword.
new
keyword is not only associated with class
. it can be used with function also.
The new
keyword executes 4 step process:
The
new
keyword creates a brand new empty JS object. andthis
is pointing to the object.It does a process of linking.
It calls the function with
this
property assigned to the empty object it created before. the moment it calls the functionthis
(everywhere) refers to the same empty object.The function execution stats. if the function doesn't return any specific object, then it automatically returns
this
. otherwise, it returns the object returned by you.