Closure

Closure exercises

by Mehmetcan Sinir

JavaScript

//Closures
var digit_name = function (n) {
    var names = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
    return names[n];
};

//the problem with the above function is that everytime it is called a new names array is created. The problem is solved with closure.

var digitName = (function () {
    var namesTwo = ["one", "two", "three", "four", "five", "six", "seven", "eight"];
    return function (n) {
        return namesTwo[n];
    };
}());

//here we invoke the function now, so here digitName is assigned to the return value of the upper function. The anonymous function(n) therefore becomes the digitName function. DigitName now returns names[n] without creating a names array everytime. function[n] has access to the variable of a returned function.


//below the step function closes over the variables of the fade function that is already returned.
function fade(id) {
    var dom = document.getElementById('someID'),
        level = 1;

    function step() {
        var h = level.toString(16);
        dom.style.backgroundColor = '#FFFF' + h + h;
        if (level < 15) {
            level += 1;
            setTimeout(step, 100);
        }
    }
    setTimeout(step, 100);
}

//a later method which causes a method on the object to be invoked in the future. Looks like this:
//my_object.later(1000, "erase", true);

if (typeof Object.prototype.later !== 'function') {
    Object.prototype.later = function (msecs, method) {
        var that = this, //get the value of this for inner functions
            //get the args after the first two
            args = Array.prototype.slice.apply(arguments, [2]);
        if (typeof method === 'string') {
            //we make the entered string the actual method of that, I mean this
            method = that[method];
        }
        setTimeout(function () {
            method.apply(that, args);
        }, msec);
        return that;
    };
}