Aug 17, 2014

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 = 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.

How to add properties to object - Create Instance Methods

Employee.prototype.combiner = function() {
    return + " "+ 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()

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 '+;
}; = "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.
> = "Nikhil"
> = "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 

Location: Hyderabad, Telangana, India