Object Oriented Programming in Javascript

Object Oriented Programming concept in Javascript is very similar to other object oriented programming language concept for example : C++, JAVA, C#, Python, PHP, Ruby and Objective-C

This is not the Rocket Science, it very simple if you already have the knowledge of OOPS in any programming language.

Ok. Lets start with the introduction of Object Oriented Javascript.

JavaScript has several objects included in its core; for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.


           Example: alert(Math.random());


Every object in JavaScript is an instance of the object Object and therefore inherits all its properties and methods.

Javascript Class:
JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person


          Example: function Person() { }


Javascript Object (Class Instance):
To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.

In the example below we define a class named Person and we create two instances (person1 and person2).

          function Person() { }

var person1 = new Person();

var person2 = new Person();


Javascript Property (object attribute):
Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly.

Working with properties from within the class is done by the keyword this, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property; this is the same syntax used by C++, Java, and a number of other languages. (Inside the class the syntax this.Property is used to get or set the property's value.)

In the example below we define the gender property for the Person class and we define it at instantiation.


function Person(gender) {

  this.gender = gender;

  alert('Person instantiated');


var person1 = new Person('Male');

var person2 = new Person('Female');

//display the person1 gender

alert('person1 is a ' + person1.gender); // person1 is a Male


This is just a sample of Object Oriented Javascript Programming, Please read below article for details.


Object Oriented Programming in Javascript Object Oriented Programming in Javascript Reviewed by Web Technology Funda on 11:53:00 PM Rating: 5

No comments

Free! Free!Free! Subscribe to Get Free PHP (Magento) tutorial Update in Your Inbox!!! Hurry Up!!!