HTML and CSS Reference
In-Depth Information
that exposes the internal [[Prototype]] property. ECMAScript 5 (ES5) has
standardized this feature as the new method Object.getPrototypeOf
(object) , giving you the ability to look up an object's [[Prototype]]. In browsers
in which __ proto __ is not available, we can sometimes use the constructor
property to get the [[Prototype]], but it requires that the object was in fact created
using a constructor and that the constructor property is set correctly.
7.3.3 Implementing super
So, JavaScript has no super , and it is not possible to traverse the prototype chain
in a standardized manner that is guaranteed to work reliably cross-browser. It's still
possible to emulate the concept of super in JavaScript. Listing 7.30 achieves this
by calling the Circle constructor from within the Sphere constructor, passing
the newly created object as the this value.
Listing 7.30 Accessing the Circle constructor from within the Sphere
function Sphere(radius) {, radius);
Running the tests confirms that sphere objects still work as intended. We can
employ the same technique to access “super methods” from other methods as well.
In Listing 7.31 we call the area method on the prototype.
Listing 7.31 Calling a method on the prototype chain
Sphere.prototype.area = function () {
return 4 *;
Listing 7.32 shows a simple test of the new method.
Listing 7.32 Calculating surface area
"test should calculate sphere area": function () {
var sphere = new Sphere(3);
assertEquals(113, Math.round(sphere.area()));
Search WWH ::

Custom Search