2 Mar 2010

JavaScript Closure by an Example


function func_c() {
var s_c1 = ' the word "funcy" means ';

function func_b() {
var s_b1 = "http://www.urbandictionary.com/define.php?term=funcy";

var func_a = function() {
var s_a1 = 'According to the <a href="'+
s_b1 + '">' + s_b2 + '</a>' +
s_c1 + s_c2 + s_this;
return s_a1;
} // func_a

var s_b2 = "Urban Dictionary"
return func_a;
} // func_b

var s_c2 = ' actually "trashy", but ';
var ff_a=func_b()
return ff_a;
} // func_c

var s_this = 'it sure sounds like "dirty" in a sexual context.';
var fun = func_c();
var s_sentence = fun();
document.write(s_sentence);


The example can be executed online over here and it outputs a string

According to the Urban Dictionary the word "funcy" means actually "trashy", but it sure sounds like "dirty" in a sexual context.

The thing to notice is how the variables, s_b1,s_b2,s_c1,s_c2,s_this are available to the function func_a, even when the func_a is called outside of the func_c. According to Justin Rogers that can cause memory leaks.

No comments: