Introduction

Javascript is Prototype-based programming is a 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 JS know as Prototype-based programming

Now we will learn Method in Javascript classes.

Please follow following steps to understand how to create methods in Javascript Classes

i)      Creating Class in javascript


Following syntax is used for declaring class in JS


function Emp(NAME) {  
   alert("EMP Instantiated");  
    this.NAME = NAME;
    }


Here Emp can be act as Class in JS and this.NAME would act as property.


Body of Emp act as constructor as called as soon we create object of class 


ii)      Defining Methods of Javascript classes  


Emp.prototype.Fun1 = function ()
  {  
  alert("EMP NAME is :" + this.NAME );
 }


We can create method using above syntax. Here Fun1 would act as method of


EMP  class


Object Oriented Javascript –Part II

 iii) Calling functionsvar Emp1 = new Emp('DEVESH');
var Emp2 = new Emp('ROLI');
 
        Emp1.Fun1();
        Emp2.Fun1()
   }

Here we have created two instance of EMP these are EMP1 and EMP2 and passing

parameter to constructor to assign NAME Property

Using EMP1.Fun1() and EMP2.Fun1() we are calling the functions

We have defined alert inside this function 


Object Oriented Javascript –Part II 


iv)          Running the code


After running the code we will get two alert each for EMP1.fun1() and Emp2.Fun1(); 


Object Oriented Javascript –Part II  


v)         Other ways to create Javascript objects


We can create object in JS in following way also 


var EMP = {
firstName:"ROLI",
lastName:"GUPTA",
age:28,
sex:"F"
};
vi)        Accessing EMP objects 


Object Oriented Javascript –Part II 


alert("EMP NAME: " + EMP.firstName + " " + EMP.lastName + " EMP AGE: " + EMP.age + "  EMP SEX : " + EMP.sex); 


Complete 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);

 





vii) Running the code :

Object Oriented Javascript –Part II 

viii)            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 fullName method inside EMP class

It returns join of fname and lname 


Running the code

Object Oriented Javascript –Part II 


Conclusion 

This document explains Methods in JavaScript classes

  Modified On Nov-29-2017 08:46:10 PM

Leave Comment