Thursday, September 20, 2012

Javascript Function Fun

Functions in Javascript are strange and interesting things.
They can be anonymous.
function() {
    alert( "This is a perfectly valid construction!" );
}

They can create objects.
function cat() {
    this.meow = function() { alert( "meow" ); }
}
var myCat = new cat();
myCat.meow(); // pops an alert box saying "meow"

They can be overridden on the fly.
myCat.meow = function() { alert( "nyan nyan nyan" ); }
myCat.meow(); // nyan nyan nyan...
They recognize scope.
var x = 12;
function addThis() {
    var y = 1;
    return x + y;
}
alert( addThis() ); // alerts 13
alert( y ); // undefined because y only exists in the scope of addThis

They can be nested.
function outer() {
    var x = 9;
    function inner() { return x + 3; }
    return inner();
}
alert( outer() ); // alerts 12

They obey closure.
function takesParam(param) {
    var temp = "I received param " + param;
    return function() {
        alert( temp );
    }
}
var result = takesParam("Hi");
result(); // alerts "I received param Hi"

They get bloggers talking about Javascript objects.

No comments:

Post a Comment