Introduction
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.
I have already explained the basics of OOP in JavaScript so it would be great if you go through with the following link.
Object-Oriented Programming in JavaScript: Part 1
In the last article we already discussed the following things:
- Classes in JavaScript
- Constructor in JavaScript
- Properties in JavaScript
- Object of JavaScript classes
Now we will learn methods in JavaScript classes.
Use the following procedure to create a sample to help understand how to create methods in JavaScript classes.
- Creating Class in JavaScript
The following syntax is used for declaring a class in JavaScript:
- function Emp(NAME) {
- alert("EMP Instantiated");
- this.NAME = 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.
- Defining Methods of JavaScript classes
- Emp.prototype.Fun1 = function ()
- {
- alert("EMP NAME is :" + this.NAME );
- }
We can create a method using the syntax above. Here Fun1 would act as a method of the EMP class.
- Calling functions
- var 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.
We have defined an alert inside this function:
- Running the code
After running the code we will get two alerts, each for EMP1.fun1() and Emp2.Fun1();
- Other ways to create JavaScript objects
We can create an object in JavaScript in the following way also:
- var EMP = {
- firstName:"ROLI",
- lastName:"GUPTA",
- age:28,
- sex:"F"
- };
- Accessing EMP objects
- alert("EMP NAME: " + EMP.firstName + " " + EMP.lastName + " EMP AGE: " + EMP.age + " EMP SEX : " + EMP.sex);
-
- lete Code
-
- var EMP = {
- firstName: "ROLI",
- lastName: "GUPTA",
- age: 28,
- sex: "F"
- };
- alert("EMP NAME: " + EMP.firstName + " " + EMP.lastName + " EMP AGE: " + EMP.age + " EMP SEX : " + EMP.sex);
- Running the code
- Defining Methods
- var 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 the code
Conclusion
This document explains methods in JavaScript classes.