JavaScript_Succinctly
Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Chapter 12 The this Keyword<br />
Conceptual overview of this and how it refers to objects<br />
When a function is created, a keyword called this is created (behind the scenes),<br />
which links to the object in which the function operates. Said another way, this is<br />
available to the scope of its function, yet is a reference to the object of which that<br />
function is a property or method.<br />
Let’s take a look at the cody object from Chapter 1 again:<br />
Sample: sample98.html<br />
<br />
var cody = {<br />
living: true,<br />
age: 23,<br />
gender: 'male',<br />
getGender: function () { return cody.gender; }<br />
};<br />
console.log(cody.getGender()); // Logs 'male'.<br />
<br />
Notice how inside of the getGender function, we are accessing the gender property<br />
using dot notation (e.g., cody.gender) on the cody object itself. This can be rewritten<br />
using this to access the cody object because this points to the cody object.<br />
Sample: sample99.html<br />
<br />
var cody = {<br />
living: true,<br />
age: 23,<br />
gender: 'male',<br />
getGender: function () { return this.gender; }<br />
};<br />
console.log(cody.getGender()); // Logs 'male'.<br />
<br />
104