Object Properties and Methods
As we discussed earlier, all objects in JavaScript inherit from the Object class. While more specialized classes, such as the built-in String class or a user-defined Complex class, define properties and methods of their own, all objects, whatever their class, also support the properties and methods defined by the Object class. Because of their universality, these properties and methods are of particular interest.
The constructor Property
Starting with
JavaScript 1.1, every object has a constructor
property that refers to the constructor function used to initialize
the object. For example, if I create an object o
with the Complex( )
constructor, the property
o.constructor
refers to
Complex
:
var o = new Complex(1,2); o.constructor == Complex; // Evaluates to true
Each Complex object (or object of whatever type) does not have its
own unique constructor
property, of course;
instead, this property is inherited from the prototype object. As
discussed earlier in this chapter, JavaScript creates a
prototype
object for each constructor function you define
and
assigns that object to the
prototype
property of the constructor. What I did
not reveal earlier, however, is that the prototype object is not
initially empty. When created, it includes a
constructor
property that refers to the
constructor function. That is, for any function f
,
f.prototype.constructor
is always equal to
f
(unless we set it to something else).
Since the constructor function defines the ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.