JS: Good parts - Ch.4 - Functions

closures

by Denise Nepraunig

JavaScript

/* 
All texts and infos I have taken from:
'JavaScript: The Good Parts' by Douglas Crockford
*/

// closure
// inner functions have access to outer functions variables
// even iv the outer function "doesn't exist" anymore

var myObject = (function() {
    var _value = 0;
    return {
        increment: function increment(inc) {
            _value += typeof inc === 'number' ? inc : 1;
        },
        getValue : function getValue() {
            return _value;
        }
    }
}());

myObject.increment(1);
// you could do this but you should not do this! 
// obj._value is not the same as the private variable!!!
 myObject._value = 5;

console.log(myObject.getValue());

var quo = function quo(status) {
    return {
        getStatus: function getStatus(){
            return status;
        }
    }
};
var myQuo = quo("my status quo");
console.log(myQuo.getStatus());

var fade = function fade(node) {
    var level = 1;
    var step = function step() {
        var hex = level.toString(16);
        node.style.backgroundColor = '#FFFF' + hex + hex;
        if (level < 15) {
            level++;
            setTimeout(step, 250);
        }
    };
    setTimeout(step, 250);
};

fade(document.body);