Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: Define objects using constructor function

In previous posts, I explained the creation of object using literal notation. Javascript provides another way to create object, using Constructor Function. As per convention, constructor function name should start with capital letter.

You can define constructor function for an Employee like below.

function Employee(firstName, lastName, id){
         this.firstName = firstName;
         this.lastName = lastName;
         this.id = id;
}

You can instantiate object for the constructor function using new keyword like below.

var emp1 = new Employee("Hari Krishna", "Gurram", 123);

You can create any number of objects from the constructor function.

object.html





objects



"text/javascript">
function Employee(firstName, lastName, id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}

function printEmployee(employee) {
for (property in employee) {
document.write(property + " : " + employee[property] + "
"
);
}
document.write("
"
);
}

/* Create an object of type Employee */
var emp1 = new Employee("Hari Krishna", "Gurram", 123);
var emp2 = new Employee("Sankalp", "Dubey", 987);

printEmployee(emp1);
printEmployee(emp2);





Open above page in browser, you can able to see following lines.

firstName : Hari Krishna
lastName : Gurram
id : 123

firstName : Sankalp
lastName : Dubey
id : 987

One intresting thing about JavaScript objects is, you can always add new properties for an existing object.
                                   
emp1.city = "Bangalore";
Above statement adds property city to the Employee emp1.                                    
object.html






objects



"text/javascript">
function Employee(firstName, lastName, id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}

function printEmployee(employee) {
for (property in employee) {
document.write(property + " : " + employee[property] + "
"
);
}
document.write("
"
);
}

/* Create an object of type Employee */
var emp1 = new Employee("Hari Krishna", "Gurram", 123);
var emp2 = new Employee("Sankalp", "Dubey", 987);

emp1.city = "Bangalore";
emp2.country = "India";

printEmployee(emp1);
printEmployee(emp2);





Open above page in browser, you will get following data.
firstName : Hari Krishna
lastName : Gurram
id : 123
city : Bangalore

firstName : Sankalp
lastName : Dubey
id : 987
country : India



Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: Define objects using constructor function

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×