-
-
Save thurt/34087583a3caf1405e9c to your computer and use it in GitHub Desktop.
(function() { | |
var Validator = (function() { | |
var Validator = function(options) { | |
... | |
}; | |
Validator.prototype.foo = function foo() { | |
... | |
}; | |
return Validator; | |
})(); | |
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') | |
module.exports = Validator; | |
else | |
window.Validator = Validator; | |
})(); |
Note: This last solution is less verbose than example 1, but it is also less ideal in a Node run-time because this === global
--meaning that we are blindly putting all objects in global scope (greater potential for unintended name collision).
In the first example, we are putting the object on module.exports
, which will be in a local variable of the calling module.
As for a browser environment, all of these possibilities will blindly be adding to the window (global scope).
If a project goes beyond a few script tags, then I think the best alternative is to use browserify instead of script tags.
browserify will create a functioning "local module system" within a javascript file which can bundle all the individual scripts. While there is some overhead to add the local module system into the javascript, it is worth it in terms simplifying deployment and reducing the number of HTTP requests (usually means a faster loading web page).
Another alternative: