Tuesday 15 November 2016

JavaScript Class


Class in JavaScript

JavaScript ECMAScript 5, does not have class type. So it does not support full object oriented programming concept as other languages like Java or C#. However, you can create a function in such a way so that it will act as a class.
The following example demonstrates how a function can be used like a class in JavaScript.

 As you know, we can create an object of any function using new keyword, so person1 object is created with new keyword. So now, Person will act as a class and person1 & person2 will be its objects (instances). Each object will hold their values separately because all the variables are defined with this keyword which binds them to particular object when we create an object using new keyword.
So this is how a function can be used like a class in the JavaScript.

Add Methods in a Class:

We can add a function expression as a member variable in a function in JavaScript. This function expression will act like a method of class.

In the above example, the Person function includes function expression that is assigned to a member variable getFullName. So now, getFullName() will act like a method of the Person class. It can be called using dot notation e.g. person1.getFullName().

Constructor:

In the other programming languages like Java or C#, a class can have one or more constructors. In JavaScript, a function can have one or more parameters. So, a function with one or more parameters can be used like a constructor where you can pass parameter values at the time or creating an object with new keyword.

In the above example, the Person function includes three parameters FirstName, LastName and Age. These parameters are used to set the values of a respective property.

Note :  Please notice that parameter assigned to a property, if parameter value is not passed while creating an object using new then they will be undefined.


















No comments: