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.

};<br />

'age': 23,<br />

'gender': 'male',<br />

'getGender': function () { return cody.gender; }<br />

console.log(cody); // Logs the cody object and its properties.<br />

<br />

<br />

It’s not necessary to specify properties as strings unless the property name:<br />

Is one of the reserved keywords (e.g., class).<br />

Contains spaces or special characters (anything other than numbers, letters, the<br />

dollar sign ($), or the underscore (_) character).<br />

Starts with a number.<br />

Notes<br />

Careful! The last property of an object should not have a trailing comma. This will cause<br />

an error in some <strong>JavaScript</strong> environments.<br />

All objects inherit from Object.prototype<br />

The Object() constructor function in <strong>JavaScript</strong> is special, as its prototype property is<br />

the last stop in the prototype chain.<br />

In the following sample, I augment the Object.prototype with a foo property and then<br />

create a string and attempt to access the foo property as if it were a property of the<br />

string instance. Since the myString instance does not have a foo property, the<br />

prototype chain kicks in and the value is looked for at String.prototype. It is not<br />

there, so the next place to look is Object.prototype, which is the final location<br />

<strong>JavaScript</strong> will look for an object value. The foo value is found because I added it, thus<br />

it returns the value of foo.<br />

Sample: sample75.html<br />

<br />

Object.prototype.foo = 'foo';<br />

var myString = 'bar';<br />

87

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

Saved successfully!

Ooh no, something went wrong!