Friday, September 21, 2012

JavaScript Tips and Tricks-8

Importance of constructor in javascript-
Check the following code -
        function Circle(radius){
            this.radius = radius;
            this.area = function(){
                return this.radius * this.radius * Math.PI;
            }
        }
       var c1 = new Circle(5);
        var c2 = {};
        Circle.call(c2,5);
       alert(c1 instanceof Circle); //true --1
        alert(c2 instanceof Circle); //false --2
        alert(c1.constructor == Circle); //true --3
        alert(c2.constructor == Circle); // false --4
Above code depict the difference between using "new" operator and calling call method on class to create new object. As you can check the output of statement 1,2,3 and 4.
"new" is equivalent to following 4 statements -
        var c2 = {};
        c2.constructor = Circle;
        c2.__proto__ = Circle.prototype;
        Circle.apply(c2,[5]);
Thus if we use "new" statement to create new object we get proper inheritance.

__proto__ Vs prototype-
__proto__ - Runtime uses to look at the parent object to resolve the properties, we can say it to be runtime reference to the parent object. All the object has __proto__ property.
prototype - It is special property of function and function only, to which "new" operator uses to copy onto the __proto__. It can be considered as template. All the function has prototype.


Function as return value-
Its always possible to return function as an object. lets see what happens in following example -
        function func1(param1){
            var counter = 0;
            return function(param2){
                return param2 + '-' + param1;
            }
        }
        var myvar1 = func1('firstcall');
        var myvar2 = func1('firstcall');;
        alert(myvar2 === myvar1); // false
If we assign the same returned function to myvar1 and myvar2, still its not equal because its 2 different instances of function.

No comments:

Post a Comment