HTML and CSS Reference
In-Depth Information
When we assign a new object to Circle.prototype , JavaScript no longer
creates a constructor property for us. This means that the [[Get]] for con-
structor will go up the prototype chain until a value is found. In the case of our
constructor, the result is Object.prototype whose constructor property
is Object , as seen in Listing 7.20.
Listing 7.20 Broken constructor property
"test constructor is Object when prototype is overridden":
function () {
function Circle() {}
Circle.prototype = {};
assertEquals(Object, new Circle().constructor);
Listing 7.21 solves the problem by assigning the constructor property
Listing 7.21 Fixing the missing constructor property
Circle.prototype = {
constructor: Circle,
// ...
To avoid the problem entirely, we could also extend the given prototype prop-
erty in a closure to avoid repeating Circle.prototype for each property. This
approach is shown in Listing 7.22.
Listing 7.22 Avoiding the missing constructor problem
(function (p) {
p.diameter = function () {
return this.radius * 2;
p.circumference = function () {
return this.diameter() * Math.PI;
p.area = function () {
return this.radius * this.radius * Math.PI;
Search WWH ::

Custom Search