How to add attributes to an Object and hence to all existing instances of that Object in JavaScript

The following is the way to define an Object and instantiate it in JavaScript

var Student=new function(fn, ln)//Student is a new Object with the following definition
//Now we can instantiate Student as follows-
var st1=new Student("rajesh", "paul");
//Now st1.first_name="rajesh" and st1.last_name="paul"

But say you have to add another property to the Object Student. The following is the way-


Now all the Existing instances and the future instances of the Object Student will have address=”abcd…” i.e. st1.address==”abcd…”.

This approach is applicable when you need to add a new attribute with a predefined value.

More to study from this Stackoverflow question:

Use of ‘prototype’ vs. ‘this’ in Javascript?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s