All pastes #455235 Raw Edit

Matt Nordhoff

public javascript v1 · immutable
·published 2007-04-24 02:19 UTC
rendered paste body
// Instead of using...var MyCoolThing = {   i: 0,   increment: function() { MyCoolThing.i++; },   decrement: function() { MyCoolThing.i--; }};// ...for a simple object, one might use...var MyCoolThing = function() {   var i = 0;   return {      increment: function() { i++; },      decrement: function() { i--; }   };}();// ...to keep the i property private from the final object and so that one// doesn't have to always type "MyCoolThing." in front of everything. What// affect does this have on browser compatability? Any that one cares about (if// it breaks Netscape 4, I think I'll live)?//// I often also see...var MyCoolThing = (function() {   var i = 0;   return {      increment: function() { i++; },      decrement: function() { i--; }   };})();// ...with ( ) around the function() { ... }. What affect does this have? It// doesn't seem to make a difference with how it functions.//// I've noticed that .toSource() on an object adds ( ) around function methods// (and around the object itself).//// Is using ( ) correct, with the JS interpreter just implying it when the// coder doesn't put it there (like the ; at the end of a line)?//// Is it just used to show people reading the code that it's going to be a// closure and not a function (should it be called a closure or something else// in this case?), without mattering to the JS interpreter?