- Ideally, all JavaScript resides in .js files which are imported
<script src="myscript.js"></script>
- Since multiple scripts might be used in a single page, there is
a danger that they use the same global variables or function identifiers
- All functions and variables share the same global namespace in the
Window
object
- Browser add-ons or extensions
also use JavaScript which could introduce collisions and conflicts
- Best to wrap all your variables and functions in a "package" via an object
var myPackage = {
name: "Bob Smith",
location: "Searcy, AR";
sayHello: function() { alert("Hello, " + this.name); }
};
- Yahoo Module Pattern
uses an immediately invoked anonymous function (allows for private and public properties
and methods)
myOrg.myProject.myModule = function() {
// "private" variables
var myPrivateVar = "Only accessible from within myOrg.myProject.myModule."
// "private" method
var myPrivateMethod = function() {
consol.log("Only accessible from within myOrg.myProject.myModule");
}
// Return object with public properties and methods
return {
myPublicProperty: "Accessible as myOrg.myProject.myModule.myPublicProperty."
myPublicMethod: function() {
console.log("I'm accessible as myOrg.myProject.myModule.myPublicMethod.");
// Within myProject there is access to "private" vars and methods
console.log(myPrivateVar);
console.log(myPrivateMethod());
// Access public members using "this"
console.log(this.myPublicProperty);
}
};
}(); // Execute immediately
- To ensure you are not using any global variables, use
strict mode (see below)