I started to read the source code for stampit js yesterday, and found an interesting way of enclose function variables in an object by calling apply()
instance = fn.apply(instance, arguments) || instance;
How does this really work? And why does the following code line not work?
instance = fn.apply(instance, arguments);
A longer example:
var createFoo = function() {
var foo = {},
fn = function() {
var i = 0;
this.increment = function() {
i++;
};
this.get = function() {
return i;
};
};
foo = fn.apply(foo, arguments) || foo;
return foo;
}, foo = createFoo();
test('foo test', function () {
foo.increment();
equal(foo.get(), 1, 'pass');
});
var createBar = function() {
var bar = {},
fn = function() {
var i = 0;
this.increment = function() {
i++;
};
this.get = function() {
return i;
};
};
bar = fn.apply(bar, arguments);
return bar;
}, bar = createBar();
test('bar tests', function () {
bar.increment(); /* undefined */
});