When using a module-esq pattern to allow chaining of methods, how long do the returned objects last before being garbage collected? I really like the way jquery allows chaining methods but I'm concerned it will pollute the memory of the page with lots of unnecessary objects if I use th pattern for my code.
here is a simple example
(function(){
// persistant variable wrapped in a closure
var prop = 'something';
//module function
function house(){
function method1(){
console.log(prop);
return this;
}
function method2(value){
prop = value
return this;
}
return {
getProp: method1,
setProp: method2
}
}
window.house = house;
})();
/*
* I am wanting to know how long the returned object will last in memory
*/
house().setProp('somethingElse');
Here is more real world example:
(function(){
// object cache to store all the elem id's that have been called
var _elemIds = {};
function get(elem){
if(!_elemIds[elem]){
// add to _elemIds object if doesn't exist
_elemIds[elem] = document.getElementById(elem);
}
var _currentElem = _elemIds[elem];
// set a css property using a json object, or get with a string
function css(){
if(typeof arguments[0] === 'object'){
for( x in arguments[0]){
_currentElem.style[x] = arguments[0][x];
}
return this;
}
else if(typeof arguments[0] === 'string'){
var l = arguments.length;
// if more than one argument return an array
if(l > 1){
var ret = [];
for (var i = 0; i < l; i++) {
if(_currentElem.style[arguments[0]] !== ''){
ret.push(_currentElem.style[arguments[i]]);
} else {
ret.push(window.getComputedStyle(_currentElem, null)[arguments[i]]);
}
}
return ret;
} else {
if(_currentElem.style[arguments[0]] !== ''){
return _currentElem.style[arguments[0]];
} else {
return window.getComputedStyle(_currentElem, null)[arguments[0]];
}
}
}
}
// change the color of the text
function color(color){
_currentElem.style.color = color;
return this;
}
// log the current element
function test(){
console.log('currentElem id: ' + _currentElem.id);
return this;
}
// return the public methods
return {
css: css,
current: test,
color: color
}
};
// set the get method to the global object
window.get = get;
})();
to access the methods from the above code you would use something like
get('elemId').css(('prop': 'value'}).current().css('prop');
thanks for any answers.
Cheers,
Andrew