Software Studio: 3 Closure Examples
Software Studio: 3 Closure Examples
studio
3 closure examples
Daniel Jackson
seq.c;}
> seq.c = 0
> seq()
note: violation of
1
encapsulation!
> seq()
counter, revisited
whats going on?
local var is updated inside fun
cant be accessed outside
said to be encapsulated
make_seq = function () {
var c = 0;
return function () {
c += 1;
return c;
return function () {
c += 1;
return c;
...
> seq()
> seq()
to start at 0.
how to do this?
fibonacci
fibonacci function
what scope is fib bound in?
note use of var
by default, you should
make all variables local
if (i < 2) return 1;
a problem
testing golden ratio property
try fib(20)/fib(19) etc
at fib(34), gets very slow...
memoizing to rescue!
result = f(i);
memo[i] = result;
return result;
return fm;
if (i < 2) return 1;
});
an abstract type
Sample = function
var total = 0;
var count = 0;
result = {
add: function
avg: function
sum: function
};
return result;
};
() {
> s.add(1);
s.add(2);
s.add(6);
> s.avg();
() { return total/count; },
() { return total; }
> s.sum();
MIT OpenCourseWare
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.