JavaScript is a prototype-based programming style of object-oriented programming in which classes are not present.
It can support OOP because it supports inheritance through prototyping as well as properties and methods.
Object-Oriented Programming in JavaScript is known as prototype-based programming
We will learn about below
1. Creating Class in JavaScript
the following syntax is used for declaring a class in JavaScript:
javascriptfunction Emp() { alert('Emp instantiated'); }
Here Emp can act as a class in JavaScript.
The body of Emp acts as a constructor and is called as soon as we create an object of the class.
2. Creating Objects of Emp Class
Using the following syntax we can create an object of the Emp class:
javascriptvar Emp1 = new Emp();
As soon as we create an object of the Emp class the constructor will be called.
Here the above function Emp would be treated as a class in JavaScript.
Running the code : An alert will be shown on the page-load of the web form
3. Properties of class
We can define the properties of a class in the following way:
javascriptfunction Emp(firstname) { alert('Emp instantiated'); this.firstname = firstname; } var Emp1 = new Emp("Devesh is Emp of GENPACT INDIA"); alert(Emp1.firstname);
Running code
4. Methods in JavaScript
Consider code below
javascriptfunction Emp(NAME) { alert("EMP Instantiated"); this.NAME = NAME; } Emp.prototype.Fun1 = function () { alert("EMP NAME is :" + this.NAME ); }
Here Emp can act as a class in JavaScript and this.NAME would act as a property.
The body of Emp acts as the constructor and is called as soon as we create an object of the class
Calling Functions
javascriptvar Emp1 = new Emp('DEVESH'); var Emp2 = new Emp('ROLI'); Emp1.Fun1(); Emp2.Fun1() }
Here we created two instances of EMP, EMP1 and EMP2 and passed a parameter to the constructor to assign a NAME Property.
Using EMP1.Fun1() and EMP2.Fun1() we are calling the functions.
Running the code
5. Other ways to create JavaScript objects
javascriptvar EMP = { firstName:"ROLI", lastName:"GUPTA", age:28, sex:"F" };
javascriptalert("EMP NAME: " + EMP.firstName + " " + EMP.lastName + " EMP AGE: " + EMP.age + " EMP SEX : " + EMP.sex);
Running code
Another way to Define methods
javascriptvar EMP = { firstName: "ROLI", lastName: "GUPTA", age: 28, sex: "F", fullName: function () { return this.firstName + " " + this.lastName } }; alert("Full name is: "+EMP.fullName());
We have defined the fullName method inside the EMP class.
It returns the join of fname and lname.
Running code
We have learnt OOPS in Javascript
Thanks.
Copyrights © 2024 letsupdateskills All rights reserved