Object creation in JavaScript : Object Oriented Programming and Prototypal Object Creation

In JavaScript most common ways to create Objects are - Object Oriented Programming (OOP) way  and Prototypal Object Creation way. In this post we will see OOP way followed by Prototypal way.

Object Oriented Programming - OOP Style object creation 


function Employee(name,designation ) {
    var new_employee = this; // 'new' object

    new_employee.name = name;
    new_employee.designation = designation;
}//Employee is a constructor 
var emp1 = new Employee('Nikhil', 'SE');
var emp2 = new Employee('Ranjan', 'SSE');

In JavaScript, as convention says, function name with Uppercase first letter is a constructor. Here Employee is a constructor which creates object and assign properties values passed to it as arguments.
Two objects emp1 and emp2 created using Employee() constructor.  Verify the same with following execution in console.
> emp1.name
"Nikhil"
>emp2.designation
"SSE"
>emp2.hasOwnProperty('name')
true
>emp1.hasOwnProperty('designation')
true

How to add properties to object - Create Instance Methods


Employee.prototype.combiner = function() {
    return this.name + " "+ this.designation;
}

Here prototype is another object. "combiner" a function is added as properties of prototype object and it is available for all objects. Execute combiner methods on an object created earlier
> emp1.combiner()
"Nikhil-->SE"



Prototypal Object Creation - JavaScript way to create Object !!

function Employee() {}; // no properties
var emp1   = new Employee(),
    emp2  = new Employee();

//Add properties for all objects  
Employee.prototype.welcome = function () {
    return 'Welcome '+ this.name;
};
Employee.prototype.name = "dummy";

Above sample code creates an empty Constructor without any properties. Object is created without any properties and at the end we add properties to all objects. Set properties value for emp1 and emp2 and execute welcome function on these objects.
> emp1.name = "Nikhil"
> emp2.name = "Ranjan"
> emp1.welcome()
"Welcome Nikhil"


How to create properties for specific object - Add properties to object instead of prototype object.

emp1.dowork = function () {
    return 'work started....';
}//dowork function is not added to prototype 

Post a Comment

Previous Post Next Post