Sunday 30 September 2018

JavaScript: valueOf: Convert object to primitive type

‘valueOf’ method is called when JavaScript requires to convert an object to primitive type.

valueOf.html
<!DOCTYPE html>

<html>

<head>
    <title>valueOf example</title>
</head>

<body>
    <script type="text/javascript">
        employee = {
            id: 123,
            name: "Hari krishna",
            salary: 25000,

            valueOf: function() {
                return this.salary;
            }
        }

        var emp1 = Object.create(employee);

        var emp2 = Object.create(employee);
        emp2.id = 514;
        emp2.name = "Sailaja"
        emp2.salary = 50000;

        document.write("Total salaries of employees : " + (emp1 + emp2));
    </script>
</body>

</html>


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

Total salaries of employees : 75000

document.write("Total salaries of employees : " + (emp1+emp2));
In above statement, I tried to add two employee objects, internally JavaScript converts this emp1 and emp2 to primitive values using valueOf method.



Previous                                                 Next                                                 Home

No comments:

Post a Comment