Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

II. Programming Practices > 6. Avoid Globals

Chapter 6. Avoid Globals

The JavaScript execution environment is unique in a lot of ways. One of those ways is in the use of global variables and functions. The default JavaScript execution environment is, in fact, defined by the various globals available to you at the start of script execution. All of these are said to be defined on the global object, a mysterious object that represents the outermost context for a script.

In browsers, the window object is typically overloaded to also be the global object, so any variable or function declared in the global scope becomes a property of the window object. For example:

var color = "red"

function sayColor() {
    alert(color);
}

console.log(window.color);              // "red"
console.log(typeof window.sayColor);    // "function"

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint