software
studio
3 closure examples
Daniel Jackson
counter, from before
> seq = function () {
seq.c += 1; return seq.c;}
function () {seq.c += 1; return
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;
make_seq = function (c) {
return function () {
c += 1;
return c;
> seq = make_seq(0)
...
> seq()
> seq()
suppose we always want
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
var fib = function (i) {
if (i < 2) return 1;
return fib(i-1) + fib(i-2);
}
a problem
testing golden ratio property
try fib(20)/fib(19) etc
at fib(34), gets very slow...
memoizing to rescue!
var memoize = function (f) {
var memo = [];
var fm = function (i) {
if (memo[i]) return memo[i];
result = f(i);
memo[i] = result;
return result;
return fm;
var mfib = memoize(function (i) {
if (i < 2) return 1;
return mfib(i-1) + mfib(i-2);
});
now mfib(1000) is instantaneous
5
an abstract type
Sample = function
var total = 0;
var count = 0;
result = {
add: function
avg: function
sum: function
};
return result;
};
() {
> var s = Sample ();
> s.add(1);
s.add(2);
s.add(6);
(v) { total += v; count++ },
undefined
> s.avg();
() { return total/count; },
() { return total; }
> s.sum();
how robust is this ADT?
what can the client break?
but see: property accessors in ECMAScript 5
MIT OpenCourseWare
http://ocw.mit.edu
6.170 Software Studio
Spring 2013
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.