17.11.2015 Views

JavaScript_Succinctly

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

window). The second way is to use the this keyword in the global scope. Each of these<br />

is detailed in the following sample.<br />

Sample: sample67.html<br />

<br />

var foo = 'bar';<br />

windowRef1 = window;<br />

windowRef2 = this;<br />

console.log(windowRef1, windowRef2); // Logs reference to window object.<br />

console.log(windowRef1.foo, windowRef2.foo); // Logs 'bar', 'bar'.<br />

<br />

In this example, we explicitly store a reference to the head object in two variables that<br />

are then used to gain access to the global foo variable.<br />

The head object is implied and typically not referenced explicitly<br />

Typically a reference to the head object is not used because it is implied. For example,<br />

in the browser environment window.alert and alert() are essentially the same<br />

statement. <strong>JavaScript</strong> fills in the blanks here. Because the window object (i.e. the head<br />

object) is the last object checked in the scope chain for a value, the window object is<br />

essentially always implied. In the next example, we leverage the alert() function<br />

which is contained in the global scope.<br />

Sample: sample68.html<br />

<br />

var foo = { // window is implied here, window.foo<br />

fooMethod: function () {<br />

alert('foo' + 'bar'); // window is implied here, window.alert<br />

window.alert('foo' + 'bar'); // window is explicitly used, with<br />

the same effect.<br />

}<br />

}<br />

foo.fooMethod(); // window is implied here, window.foo.fooMethod()<br />

<br />

81

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!