Saturday, 1 September 2018

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
<!DOCTYPE html>

<html>

<head>
    <title>objects</title>
</head>

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

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

        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);
    </script>
</body>

</html>

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

No comments:

Post a Comment