//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;
};
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.