Reputation: 3082
I've been using two versions of a JavaScript pattern for a while that I picked up from Addy Osmani called the module pattern. view it here
The first version of this pattern uses an object literal:
var x = {
b: function() {
return 'text';
},
c: function() {
var h = this.b();
h += ' for reading';
}
}
alert(x.b()) // alerts text.
while the other version uses a self executing function:
var y = (function() {
var first = 'some value';
var second = 'some other value';
function concat() {
return first += ' '+second;
}
return {
setNewValue: function(userValue) {
first = userValue;
},
showNewVal: function() {
alert(concat());
}
}
})();
y.setNewValue('something else');
y.showNewVal();
Given the examples above, are either of these two patterns (not taking into account any event listeners) garbage collection friendly (given the way they reference themselves)?
Upvotes: 1
Views: 264
Reputation: 120506
No. There's no difference as far as what becomes unreachable when.
Both use a global variable that pins the API in place, so will not be collectible until the frame is unloaded and dropped from history.
The second allocates and holds onto an extra activation frame (for module-locals first
and second
), but that's a pretty minor cost.
Upvotes: 1