Chapter 42. Avoiding Global Scope

In Lesson 39, I mentioned that it's good practice to avoid the global scope. This is crucial when you incorporate someone else's code in your page, as it helps you avoid naming conflicts between the variable and function names given in yours and the other party's code. What exactly is a naming conflict? A naming conflict occurs when you use an identifier that is used in another script on the same level of scope.

Let's look at an example. The following code is a truncated version of the eventUtility object used throughout this book:

// your code
var eventUtility = {
    addEvent : (function() {
        if (typeof addEventListener !== "undefined") {
            return function(obj, evt, fn) {
                obj.addEventListener(evt, fn, false);
            };
        } else {
            return function(obj, evt, fn) {
                obj.attachEvent("on" + evt, fn);
            };
        }
    }())
};

This code creates the eventUtility object with the addEvent() method. This code is defined in the global scope, and your event-driven code heavily relies on this particular object and method. But you wanted to add some extra functionality to your page, and you incorporated code written by someone else. It too uses a global object called eventUtility, but it's different from yours. Its code is as follows:

// third party code
var eventUtility = {
    addEventHandler : function(obj, evt, fn) {
obj.addEventListener(evt, fn, false);
    }
};

The browser loads this code after loading yours. Since they both share the same identifier and they exist on the same level of scope (global), ...

Get JavaScript® 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.