HTML and CSS Reference
In-Depth Information
The expression a instanceof b will return true whenever the internal
[[Prototype]] property of a , or one of the objects on its prototype chain, is the
same object as b.prototype .
7.2.3 Constructor Prototypes
Functions are always assigned a prototype property, which will be set as the in-
ternal [[Prototype]] property of objects created by the function when used as a con-
structor. The assigned prototype object's prototype is in turn Object.prototype
and it defines a single property, constructor , which is a reference to the con-
structor itself. Because the new operator may be used with any expression that
results in a constructor, we can use this property to dynamically create new objects
of the same type as a known object. In Listing 7.15 we use the constructor
property of a circle object to create a new circle object.
Listing 7.15 Creating objects of the same kind
"test should create another object of same kind":
function () {
var circle = new Circle(6);
var circle2 = new circle.constructor(9);
assertEquals(circle.constructor, circle2.constructor);
assertTrue(circle2 instanceof Circle);
}
7.2.3.1 Adding Properties to the Prototype
We can give our new circle objects new functionality by augmenting the proto-
type property of the constructor, much like we extended the behavior of native
objects in Section 7.1.3, Extending Objects through the Prototype Chain. Listing 7.16
adds three methods for circle objects to inherit.
Listing 7.16 Adding properties to Circle.prototype
Circle.prototype.diameter = function () {
return this.radius * 2;
};
Circle.prototype.circumference = function () {
return this.diameter() * Math.PI;
};
 
Search WWH ::




Custom Search