Saturday, 1 September 2018

JavaScript: Inheritance

JavaScript supports prototype-based inheritance, One object inherit from other object.

If you create an object by using Constructor function, that object has the property ‘prototype’ by default.

Let me give an example. I am going to define an Employee constructor function like below.

function Employee(id, firstName){
         this.id = id;
         this.firstName = firstName;
}
        
Let me define two objects using Employee constructor function.

var emp1 = new Employee(1, "Hari Krishna");
var emp2 = new Employee(2, "Sudhir");

Suppose if you want to add two more properties like organization, country to all the instances of Employee objects (for existing objects and new objects), you need to use the prototype property.

Employee.prototype.organization = "XYZ";
Employee.prototype.country = "India";

Above statement adds the properties organization and country properties to all Employee instances.

prototype.html

<!DOCTYPE html>

<html>

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

<body>
    <script type="text/javascript">
        function displayObject(obj) {
            document.write("<br />");
            for (prop in obj) {
                document.write(prop + " : " + obj[prop] + "<br />");
            }
            document.write("<br />");
        }


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

        var emp1 = new Employee(1, "Hari Krishna");
        var emp2 = new Employee(2, "Sudhir");

        displayObject(emp1);
        displayObject(emp2);

        Employee.prototype.organization = "XYZ";
        Employee.prototype.country = "India";

        displayObject(emp1);
        displayObject(emp2);
    </script>
</body>

</html>

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

id : 1
firstName : Hari Krishna


id : 2
firstName : Sudhir


id : 1
firstName : Hari Krishna
organization : XYZ
country : India


id : 2
firstName : Sudhir
organization : XYZ
country : India


Can I add methods to an object using prototype?
Yes of course, you can also add methods using prototype.

Employee.prototype.getDetails = function(){
         return "[" + this.id + " " + this.firstName + "]";
}

Above statement adds the function getDetails to Employee.

prototype.html

<!DOCTYPE html>

<html>

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

<body>
    <script type="text/javascript">
        function Employee(id, firstName) {
            this.id = id;
            this.firstName = firstName;
        }

        var emp1 = new Employee(1, "Hari Krishna");
        var emp2 = new Employee(2, "Sudhir");

        Employee.prototype.getDetails = function() {
            return "[" + this.id + " " + this.firstName + "]";
        }

        document.write(emp1.getDetails() + "<br />");
        document.write(emp2.getDetails() + "<br />");
    </script>
</body>

</html>

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

[1 Hari Krishna]
[2 Sudhir]

Inheriting properties from other object
By using prototype property, you can inherit the properties and methods of an object into other object.

var organization = {
         name : "xyz",
         city : "Bangalore"
}

function Employee(id, firstName){
         this.id = id;
         this.firstName = firstName;
}
                                                                                
I defined organization object using literal notation and created Employee constructor function.

Employee.prototype = organization;

Above statement sets the prototype of Employee to organization. So Employee instances inherit the organization properties like name and city.


prototype.html

<!DOCTYPE html>

<html>

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

<body>
    <script type="text/javascript">
        function displayObject(obj) {
            document.write("<br />");
            for (prop in obj) {
                document.write(prop + " : " + obj[prop] + "<br />");
            }
            document.write("<br />");
        }

        var organization = {
            name: "xyz",
            city: "Bangalore"
        }

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


        Employee.prototype = organization;

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

        displayObject(emp1);
    </script>
</body>

</html>

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

id : 1
firstName : Hari Krishna
name : xyz
city : Bangalore


Previous                                                 Next                                                 Home

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

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

<html>

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

<body>
    <script type="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] + "<br />");
            }
            document.write("<br />");
        }

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

</html>

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

<!DOCTYPE html>

<html>

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

<body>
    <script type="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] + "<br />");
            }
            document.write("<br />");
        }

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

</html>

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

JavaScript: Adding methods to an object

An object in JavaScript has properties and methods associated with it. For example, see the following object 'employee', it has properties firstName, lastName and id. It has methods
a.   setFirstName : sets the firstName of employee object
b.   setLastName : sets the lastName of employee object
c.   setId : sets the id of the employee object
d.   getDetails : return string representation of employee object.

var employee = {
 firstName: "no_name",
 lastName: "no_name",
 id: "-1",
    
 setFirstName: function(firstName){
  this.firstName = firstName;
 },
   
 setLastName: function(lastName){
  this.lastName = lastName;
 },
    
 setId: function(id){
  this.id = id;
 },
    
 getDetails: function(){
  return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
 }
}

Note that I used this keyword inside the methods, When a function is called from the object, this becomes a reference to the current object. By using this, we can refer current object properties.

object.html

<!DOCTYPE html>

<html>

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

<body>
    <script type="text/javascript">
        var employee = {
            firstName: "no_name",
            lastName: "no_name",
            id: "-1",

            setFirstName: function(firstName) {
                this.firstName = firstName;
            },

            setLastName: function(lastName) {
                this.lastName = lastName;
            },

            setId: function(id) {
                this.id = id;
            },

            getDetails: function() {
                return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
            }
        }

        employee.setFirstName("Hari Krishna");
        employee.setLastName("Gurram");
        employee.setId(1);

        document.write(employee.getDetails());
    </script>
</body>

</html>

Load above html in browser, you can able to see following text.

[firstName = Hari Krishna, lastName = Gurram, id = 1]


Previous                                                 Next                                                 Home

JavaScript: function scope and hoisting

If you come from languages like c, java you may have heard about block scope. In block scope, a variable defined inside a block {}, is not visible (or) accessible outside the block. JavaScript don't have block scope, it supports function level scope. A variable defined inside a function is available throughout the function.

scope.html
<!DOCTYPE html>

<html>

<head>
    <title>Function Scope</title>
</head>

<body>
    <script>
        function processData() {
            var i = 10;

            // Even though j is defined inside loop, it is available throughout the function
            for (var j = 0; j < 100; j++) {
                var k = 9999;
            }

            document.write("i = " + i + "<br />");
            document.write("j = " + j + "<br />");
            document.write("k = " + k + "<br />");
        }

        processData();
    </script>
</body>

</html>

Load scope.html in browser, you can able to see following text.

i = 10
j = 100
k = 9999

As you see the file ‘scope.html’, variables j and k are defined in for loop. Due to the concept of functional scope variable j and k are available outside the loop also.

Hoisting
Variables are visible before declaration.

var name = "Hari krishna";

function processData(){
         // Usually you may expect the value "Hari Krishna" here, but it is undefined
         document.write("name = " + name + "<br />"); // Line 1
                                   
         var name = "Deeraj"; // Line 2
                                   
         document.write("name = " + name + "<br />");
}      
                          
processData();
                          
You may think that the first line in the function prints the value “Hari Krishna”, but as I said the local variable defined in a function is available throughout the function, even though the variable 'name' defined at 2nd line, it is still visible at line 1 as undefined value. So you will get undefined.


hoisting.html

<!DOCTYPE html>

<html>

<head>
    <title>Function Scope</title>
</head>

<body>
    <script>
        var name = "Hari krishna";

        function processData() {
            document.write("name = " + name + "<br />");

            var name = "Deeraj";

            document.write("name = " + name + "<br />");
        }

        processData();
    </script>
</body>

</html>

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

name = undefined
name = Deeraj

Hoisting is applicable to nested functions also. When you declare a variable using var keyword, the hoisted variable initialization code remains same where you placed it and it has the value
undefined before the initialization. With function declaration statements, both the function name and function body are hoisted.


functionHoisting.html

<!DOCTYPE html>

<html>

<head>
    <title>Hoisting Example</title>
</head>

<body>
    <script>
        function arithmetic(a, b) {

            var result = [add(a, b), sub(a, b), mul(a, b), div(a, b)];
            return result;

            function add(a, b) {
                return a + b;
            }

            function sub(a, b) {
                return a - b;
            }

            function mul(a, b) {
                return a * b;
            }

            function div(a, b) {
                return a / b;
            }
        }

        var result = arithmetic(10, 20);
        document.write("Addition : " + result[0] + "<br />");
        document.write("Subtraction : " + result[1] + "<br />");
        document.write("Multiplicaiton : " + result[2] + "<br />");
        document.write("Division : " + result[3] + "<br />");
    </script>
</body>

</html>

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

Addition : 30
Subtraction : -10
Multiplicaiton : 200
Division : 0.5


Previous                                                 Next                                                 Home

JavaScript: Recursion

Recursion is a technique, where a function can call itself. For example, following function calculates the factorial of a number using recursion.

function factorial(n){
         if(n < 2)
                  return 1;
         return n * factorial(n-1);
}

There are three ways that a function can refer to itself.
a.   By using function name
b.   By using arguments.callee
c.   By using an in-scope variable that refers to the function

By using function name
function factorial_1(n){
         if(n < 2)
                  return 1;
         return n * factorial_1(n-1);
}

By using arguments.callee
function factorial_2(n){
         if(n < 2)
                  return 1;
         return n * arguments.callee(n-1);
}

By using an in-scope variable that refers to the function
var factorial_3 = function factorial(n){
         if(n < 2)
                  return 1;
         return n * factorial_3(n-1);
}

factorial.html
<!DOCTYPE html>

<html>

<head>
    <title>Factorial</title>
</head>

<body>
    <script type="text/javascript">
        // By using function name 
        function factorial_1(n) {
            if (n < 2)
                return 1;
            return n * factorial_1(n - 1);
        }

        // By using argument.callee
        function factorial_2(n) {
            if (n < 2)
                return 1;
            return n * arguments.callee(n - 1);
        }

        // By using in-scope variable
        var factorial_3 = function factorial(n) {
            if (n < 2)
                return 1;
            return n * factorial_3(n - 1);
        }

        document.write("Factorial of 5 is " + factorial_1(5) + "<br />");
        document.write("Factorial of 10 is " + factorial_2(10) + "<br />");
        document.write("Factorial of 20 is " + factorial_3(20) + "<br />");
    </script>
</body>

</html>

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

Factorial of 5 is 120
Factorial of 10 is 3628800
Factorial of 20 is 2432902008176640000



Previous                                                 Next                                                 Home

JavaScript: Function Arguments

In JavaScript, a function can be called using any number of arguments. Suppose if a function is defined with 4 arguments, it is not necessary to pass all the 4 arguments while calling the function.

For example,
function processData(a, b, c, d){

}

Above function can be processed like below.
processData(10);
processData(10, 20);
processData(10, 20, 30);
processData(10, 20, 30, 40);
processData(10, 20, 30, 40, 50); //50 is unnamed argument
processData(10, 20, 30, 40, 50, 60); // 50 and 60 are unnamed arguments

function.html
<!DOCTYPE html>

<html>

<head>
    <title>function arguments</title>
</head>

<body>
    <script type="text/javascript">
        function processData(a, b, c, d) {
            document.write("a = " + a + " b = " + b + " c = " + c + " d = " + d + "<br /><br />");
        }

        processData(10);
        processData(10, 20);
        processData(10, 20, 30);
        processData(10, 20, 30, 40);
        processData(10, 20, 30, 40, 50);
    </script>
</body>

</html>

Open above page in browser, you can able to see following data.
a = 10 b = undefined c = undefined d = undefined

a = 10 b = 20 c = undefined d = undefined

a = 10 b = 20 c = 30 d = undefined

a = 10 b = 20 c = 30 d = 40

a = 10 b = 20 c = 30 d = 40

Accessing unnamed arguments of a function
By using arguments keyword, you can access all the arguments passed to the function.

function processData(a){
         for(var i=0; i<arguments.length; i++) {
                  document.write(arguments[i] + " ");
         }
         document.write("<br /><br />");
}
                          
functionArgs.html

<!DOCTYPE html>

<html>

<head>
    <title>Function Arguments</title>
</head>

<body>
    <script type="text/javascript">
        function processData(a) {
            document.write("Arguments are : ");
            for (var i = 0; i < arguments.length; i++) {
                document.write(arguments[i] + " ");
            }
            document.write("<br /><br />");
        }

        processData();
        processData(10);
        processData(10, 20);
        processData(10, 20, 30);
    </script>
</body>

</html>

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

Arguments are :

Arguments are : 10

Arguments are : 10 20

Arguments are : 10 20 30


Previous                                                 Next                                                 Home