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

JavaScript: Create an object using Object.create method

In previous posts, I explained how to create Object using literal notation and by using constructor function. One difference is, you can use constructor function as prototype and define multiple objects using this prototype. But you can’t achieve the same thing using literal notation. By using Object.create() method you can create an object by choosing the prototype object for the object you want to create.


var Employee = {
         firstName: "no_name",
         lastName: "no_name",
         id: 123
};

var emp1 = Object.create(Employee);

object.html





objects



"text/javascript">
var Employee = {
firstName: "no_name",
lastName: "no_name",
id: 123
};

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

var emp1 = Object.create(Employee);
var emp2 = Object.create(Employee);

emp1.firstName = "Hari Krishna";
emp1.lastName = "Gurram";
emp1.id = 123;

emp2.firstName = "Deeraj";
emp2.lastName = "Arora";
emp2.id = 786;

printEmployee(emp1);
printEmployee(emp2);





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

firstName : Hari Krishna
lastName : Gurram
id : 123

firstName : Deeraj
lastName : Arora
id : 786



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: Create an object using Object.create method

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×