17.11.2015 Views

JavaScript_Succinctly

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Working around the nested function issue by leveraging the scope<br />

chain<br />

So that the this value does not get lost, you can simply use the scope chain to keep a<br />

reference to this in the parent function. The following sample demonstrates how, using<br />

a variable called that, and leveraging its scope, we can keep better track of function<br />

context.<br />

Sample: sample104.html<br />

<br />

var myObject = {<br />

myProperty: 'I can see the light',<br />

myMethod : function(){<br />

var that = this; // Store a reference to this (i.e. myObject) in<br />

myMethod scope.<br />

var helperFunction = function() { // Child function.<br />

// Logs 'I can see the light' via scope chain because that<br />

= this.<br />

console.log(that.myProperty); // Logs 'I can see the<br />

light'.<br />

console.log(this); // Logs window object, if we don't use<br />

"that".<br />

}();<br />

}<br />

}<br />

myObject.myMethod(); // Invoke myMethod.<br />

<br />

Controlling the value of this using call() or apply()<br />

The value of this is normally determined from the context in which a function is called<br />

(except when the new keyword is used—more about that in a minute), but you can<br />

overwrite and control the value of this using apply() or call() to define what object<br />

this points to when invoking a function. Using these methods is like saying: "Hey, call<br />

X function but tell the function to use Z object as the value for this." By doing so, the<br />

default way in which <strong>JavaScript</strong> determines the value of this is overridden.<br />

In the next sample, we create an object and a function. We then invoke the function via<br />

call() so that the value of this inside the function uses myObject as its context. The<br />

statements inside the myFunction function will then populate myObject with properties<br />

instead of populating the head object. We have altered the object to which this (inside<br />

of myFunction) refers.<br />

108

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

Saved successfully!

Ooh no, something went wrong!