Wednesday, January 9, 2013

JavaScript Tips and Tricks-9

Lets try to understand the output of following function - 

function fun(){}
var fun1 = new fun();
var fun2 = fun(); //undefined
var fun3 = fun;

fun1.newProp1 = '1';
fun3.newProp2 = '2';

alert(fun1.newProp1);//-- 1
alert(fun3.newProp2);//-- 2

var fun4 = new fun();
alert(fun4.newProp2);//undefined

if we define fun in the following way -
function fun(){ return this;}
then fun2 will not be undefined, it will be window. because fun2 = fun() actually executes the function and assign the value back to fun2.
fun3 is also just pointing at the definition of fun, but we can not write var a = new fun3(); it will be undefined.

Moreover on the heap you will see just 2 objects, fun1 and fun4(along with the original definition of course).
Lets try to find the answer for following exercise -
    function fun(){
        this.a = '1';
        b = '2';
        var c = '3';
        return this;
    }
   
    var fun1 = new fun();
    alert('fun1.a ' + fun1.a);
    alert('fun1.b ' + fun1.b);
    alert('fun1.c ' + fun1.c);

    var fun2 = fun();
    alert('fun2.a ' + fun2.a);
    alert('fun2.b ' + fun2.b);
    alert('fun2.c ' + fun2.c);

    alert('window.a ' + window.a);
    alert('window.b ' + window.b);
    alert('window.c ' + window.c);

Answer -

var fun1 = new fun();
alert('fun1.a ' + fun1.a); //1
alert('fun1.b ' + fun1.b); // undefined
alert('fun1.c ' + fun1.c); // undefined

var fun2 = fun();
alert('fun2.a ' + fun2.a); //1
alert('fun2.b ' + fun2.b); //2
alert('fun2.c ' + fun2.c); // undefined

alert('window.a ' + window.a); //1
alert('window.b ' + window.b); //2
alert('window.c ' + window.c); // undefined

No comments:

Post a Comment