The Global Object

The javaScript programs run inside a host environment (the browser). The host environment provides a global object and all global variables are actually properties of the global object.

If your host environment is the web browser, the global object is called window.

Declaring a global variable, outside of any function as below.

var a = 1;

The above global variable can be accessed in various ways:

  • As a variable 'a'
  • As a property of the global object, for example window['a'] or window.a

Now define a constructor function and call it without the new operator. In such cases this refers to the global object and all properties set with this become properties of window.

Declaring a constructor function and calling it without new, returns undefined.

function Hero(name) {
    this.name = name;
}
var h = Hero('Leonardo');

typeof h
"undefined"

typeof h.name
h has no properties

Because you had this inside Hero, a global variable (a property of the global object) called name was created.

name
"Leonardo"

window.name
"Leonardo"

If you call the same constructor function but this time using new, then a new object is returned and this refers to it.

var h2 = new Hero('Michelangelo');

typeof h2
"object"

h2.name
"Michelangelo"

The global functions can also be invoked as methods of the window object. The following two codes are the same.

parseInt('101 dalmatians')
101

window.parseInt('101 dalmatians')
101
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +