basically, without using the closure, the mixin function will be created every
time the mixin is used. By creating a closure, each of the function will be
created once, and the mixin will reference those functions every time it is
called. Since the mixin doesn't have to recreate those functions every time it
runs, its faster.
without the closure
var asRectangle = function() {
// every time this function is called, these three functions are created
// from scratch, slowing down execution time
this.area = function() {
return this.length * this.width;
}
this.grow = function() {
this.length++, this.width++;
}
this.shrink = function() {
this.length--, this.width--;
}
})();
with the closure
var asRectangle = (function() {
// these functions are 'cached' in the closure
function area() {
return this.length * this.width;
}
function grow() {
this.length++, this.width++;
}
function shrink() {
this.length--, this.width--;
}
// this function is set to asRectangle. it references the above functions
// every time it is called without having to create new ones
return function() {
this.area = area;
this.grow = grow;
this.shrink = shrink;
return this;
};
})();