Client-Side Web TechnologiesJavaScript Part II
Object Constructors• Any function called with the new operator acts as a
constructor function
• When a constructor is called the following takes
place:
• A new object instance is created
• The this variable inside the constructor function is
assigned to point to the newly created instance
• Code inside the constructor is executed
• The new instance is returned
Prototypes• A big disadvantage of constructors is that each
method of an object (being a function and functions
are objects) is created once for each instance
• A prototype is an object containing properties and
methods that are shared among all instances of a
reference type
• Each constructor function has a prototype
property that points to its prototype object
• Each prototype object has a constructor
property that points back to the constructor on
which it is a property
Prototypes (continued)• Each instance of an object created with a
constructor gets an internal pointer to the
constructor’s prototype
• In ECMAScript it is referred to as [ [ Prototype ] ]
• In ECMAScript it can be accessed via the Object.getPrototypeOf() method
• The isPrototypeOf() method can be used to
determine if an instance’s prototype pointer points to a
certain prototype
• Examples at: http://csw08724.appspot.com/Prototypes.html
Prototypes (continued)• When a property is accessed on an object for reading
• The object instance is checked to see if it exists
• Otherwise the prototype is checked to see if it exists on the
prototype
• If the prototypes are chained, then the search will continue all
the way along the chain until the property is found or the end is
reached
• When a property is added to an instance it shadows any
property on the prototype with the same name
• So we can “override” the prototype
• The hasOwnProperty() method can be used to
determine if a property or method exists on the instance
Embracing ECMAScript’s Prototypal Nature
• Some people advocate not trying to force classical
inheritance patterns on ECMAScript objects
• No new operator
• No constructor functions
• We create new objects based on existing ones and
add features to the new objects
• See the PurePrototypes.html example