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.

Clearly, the value of this is based on the context in which the function is being called.<br />

Consider that both myObject.sayFoo and sayFoo point to the same function. However,<br />

depending upon where (i.e. the context) sayFoo() is called from, the value of this is<br />

different.<br />

If it helps, here is the same code with the head object (i.e. window) explicitly used.<br />

Sample: sample101.html<br />

<br />

window.foo = 'foo';<br />

window.myObject = { foo: 'I am myObject.foo' };<br />

window.sayFoo = function () {<br />

console.log(this.foo);<br />

};<br />

window.myObject.sayFoo = window.sayFoo;<br />

window.myObject.sayFoo();<br />

window.sayFoo();<br />

<br />

Make sure that as you pass around functions, or have multiple references to a function,<br />

you realize that the value of this will change depending upon the context in which you<br />

call the function.<br />

Notes<br />

All variables except this and arguments follow lexical scope.<br />

The this keyword refers to the head object in nested functions<br />

You might be wondering what happens to this when it is used inside of a function that<br />

is contained inside of another function. The bad news is in ECMA 3, this loses its way<br />

and refers to the head object (the window object in browsers), instead of the object<br />

within which the function is defined.<br />

In the following code, this inside of func2 and func3 loses its way and refers not to<br />

myObject but instead to the head object.<br />

Sample: sample102.html<br />

<br />

106

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

Saved successfully!

Ooh no, something went wrong!