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.

console.log(cody.name); // Undefined. The value is actually set at<br />

window.name<br />

console.log(window.name); // Logs 'Cody Lindley'.<br />

<br />

The keyword this inside a prototype method refers to a constructor<br />

instance<br />

When used in functions added to a constructor’s prototype property, this refers to the<br />

instance on which the method is invoked. Say we have a custom Person() constructor<br />

function. As a parameter, it requires the person’s full name. In case we need to access<br />

the full name of the person, we add a whatIsMyFullName method to the<br />

Person.prototype so that all Person instances inherit the method. When using this,<br />

the method can refer to the instance invoking it (and thus its properties).<br />

Here I demonstrate the creation of two Person objects (cody and lisa) and the<br />

inherited whatIsMyFullName method that contains the this keyword to access the<br />

instance.<br />

Sample: sample109.html<br />

<br />

var Person = function (x) {<br />

if (x) { this.fullName = x };<br />

};<br />

Person.prototype.whatIsMyFullName = function () {<br />

return this.fullName; // 'this' refers to the instance created from<br />

Person()<br />

}<br />

var cody = new Person('cody lindley');<br />

var lisa = new Person('lisa lindley');<br />

// Call the inherited whatIsMyFullName method, which uses this to refer<br />

to the instance.<br />

console.log(cody.whatIsMyFullName(), lisa.whatIsMyFullName());<br />

/* The prototype chain is still in effect, so if the instance does not<br />

have a fullName property, it will look for it in the prototype chain. Next,<br />

we add a fullName property to both the Person prototype and the Object<br />

prototype. See the notes that follow this sample. */<br />

Object.prototype.fullName = 'John Doe';<br />

111

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

Saved successfully!

Ooh no, something went wrong!