1

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)?

3
  • I think so. Whenever you don't have anything pointing to those objects, they'll become eligible for gc (including the closure). Commented Jan 14, 2013 at 19:38
  • @bfavaretto the first one will (when i use it) usually reference it self a lot like "this.c() or this.b()" can self reference keep the main object from being GC'd? Commented Jan 14, 2013 at 19:45
  • 1
    I'm no expert, but again I don't think so (especially because this is determined on call-time in js). Commented Jan 14, 2013 at 19:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so technically speaking if i were to use the "delete" keyword on either one "var x or var y" like so "delete x or delete y" would that essentially make it garbage collectible?
@zero, no. delete window.x would. delete x is a no-op or error in strict mode I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.