4 ms·
Better namespacing: function _namespace(){}; function _namespaceLib(){}; // Define your library methods (function(){ var _private; this.g
by ed 17y ago
Better namespacing:
function _namespace(){};
function _namespaceLib(){};
// Define your library methods
(function(){
var _private;
this.getPrivate = function(){return _private};
}).apply(_namespaceLib);
// Wrap your code with the new scope
(function(){ with (_namespaceLib) {
// Do anything you want here
var local = "only visible in local scope";
// The library is now in scope
alert( this.getPrivate() );
// Define your external methods
_namespace.myAPIMethod = function(){return local};
}}).apply({});
// _private and local are not accessible
_namespace.myAPIMethod(); // returns "only visible in local scope"
- apu 17y agoI thought 'with' was generally frowned upon? Is it guaranteed to work correctly in all situations? And why is this a better namespacing method?
- ed 17y agoYes, "with": - adds an extra look-up when resolving scope - creates code that sometimes isn't immediately obvious But with this technique you basically get to forget you're writing code in a namespace. You can var myFunc; all you want without polluting the global. And you can put the library in a separate file and reference its exposed methods as if they were written in the body of your application.