HTML and CSS Reference
In-Depth Information
which classes inherit from other classes, and objects constitute instances of classes.
We'll approach the subject by continuing our study of property access.
When you read a property on an object, JavaScript uses the object's internal
[[Get]] method. This method checks if the object has a property of the given
name. If it has, its value is returned. If the object does not have such a property,
the interpreter checks if the object has a [[Prototype]] that is not null (only
Object.prototype has a null [[Prototype]]). If it does, the interpreter will
check whether the prototype has the property in question. If it does, its value is
returned, otherwise the interpreter continues up the prototype chain until it reaches
Object.prototype . If neither the object nor any of the objects in its prototype
has a property of the given name, undefined is returned.
When you assign, or put, a value to an object property, the object's internal
[[Put]] method is used. If the object does not already have a property of the given
name, one is created and its value is set to the provided value. If the object already
has a property of the same name, its value is set to the one provided.
Assignment does not affect the prototype chain. In fact, if we assign a prop-
erty that already exists on the prototype chain, we are shadowing the prototype's
property. Listing 7.3 shows an example of property shadowing. To run the test with
JsTestDriver, set up a simple project as described in Chapter 3, Tools of the Trade,
and add a configuration file that loads test/*.js .
Listing 7.3 Inheriting and shadowing properties
TestCase("ObjectPropertyTest", {
"test setting property shadows property on prototype":
function () {
var object1 = {};
var object2 = {};
// Both objects inherit Object.prototype.toString
assertEquals(object1.toString, object2.toString);
var chris = {
name: "Chris",
toString: function () {
// chris object defines a toString property that is
// not the same object as object1 inherits from
Search WWH ::

Custom Search