Anonymous functions
Like Lisp, Scheme and dynamic languages such as Python and Ruby, Javascript has syntax to support anonymous functions. Anonymous functions are also often called lambdas. One way to use anonymous functions is to bind them to object properties as shown below.
obj1 = { fun1:"zip", fun2:"nada" }
obj1.fun1 = function() { alert('fun1 here!') }
obj1.fun2 = function() { return "fun2" }
(and try the buttons above again)
Closures / lexical scoping
A closure is a function that 'remembers' its surrounding scope at the point where it was defined. This is called lexical scoping as opposed to dynamic scoping because the scope the function 'remembers' is the one defined textually (lexically) in the source code rather than the scope the inner function finds itself executing within during run-time. All Javascript functions are closures.
msg=12
function f1() { return msg }
function wrapper() {
var msg="morning"
function f2() { return msg }
alert(f1())
alert(f2())
}
Below is a technique that creates a 'factory function' by combining the closures property of a function together with the ability to define them anonymously. Factory functions are functions that spit out further functions, the scopes of which include the parameters fed to the factory function. Incidentally, the technique demonstrated below is known as currying or partial evaluation.
function mult_factory(mult) {
return function(x) { return x * mult }
}
pairs = mult_factory(2)
dozens = mult_factory(12)
function some_other() {
var mult=20
alert (dozens(10))
}
In a dynamically scoped language, function dozens(),
executing inside some_other(), would have taken
the value of mult declared there and
dozens(10) would have returned 200 instead of 120.
Another example.
a=5
b=5
c=5
x=0
function outerabc() { return a*b*c }
function createinnerabc() {
var a=1, b=2, c=3
alert('yo')
// let global 'x' remember the value outerabc()
// returned when run within this function
x = outerabc()
// create a function called innerabc1() and assign
// it to the global 'innerabc1'
innerabc1 = function() { return a*b*c }
// return a closure to the caller
return function() { return a*b*c }
}
Javascript functions are objects and have properties
Another commonality Javascript shares with languages like Lisp, Scheme, Python, Ruby, etc... are that functions also happen to be objects. This means that they can (and do) have properties.
function abracadabra(word,creature) {
alert(word+"! You are now a "+creature+"!")
}
function abracadabra2(word,repeat,creature) {
while (--repeat) alert(word+"! You are now a "+creature+"!")
}