Concept
Each object in javascript has a private property called Prototype, which is like a pointer referring to another object in every instances. Prototype is shared by all instances, so two different objects could access common properties and methods on the prototype if they have the same prototype, and modifying property on the prototype will affect the following access. Each object has its own prototype, which may also has its prototype until the Object
finally, which forms the prototype chain. Therefore, Object
is at the root of the prototype chain, the ancestor of all object instances. All objects “inherit” from Object
. Object
itself also has prototype, which is null
, while null
doesn’t has any prototype. Generally, an object i.e an array, has the prototype of Array
, which has the prototype of Object
. In the examples, the variable, prototype Array
and prototype Object
form the prototype chain. Any objects in javascript has such prototype chain, longer or shorter.
Usage
Prototype is fundamentally used for property(or method) lookup. For instance, we create an variable that is an Array
, i.e, var array = []
. Then the variable array
’s prototype is Array
, and its prototype is Object
, which make up of the prototype chain. When accessing the method toString()
, the process of the lookup will be: search array
’s own properties to see whether toString()
method exist. If so, return that function and the lookup is finished. Otherwise, search the prototype of array
, Array
, to see whether it has the method. If so, return the method and the lookup is finished. Otherwise, search the prototype of Array
, Object
, for toString()
method. If so, return the method and the lookup is finished. Otherwise, return undefined
because it reach the root of the prototype chain. Of course, Object
has toString()
method.
As property and method lookup process will enumerate all enumerable properties and methods in the object, the time for lookup will be critically longer for those instances with a long prototype chain. This may lead to performance problems if neglecting your object prototypes
Object.getPropertyOf() and Object.setPrototypeOf()
getPrototypeOf()
and setPrototypeOf()
methods provide interfaces to access and modify an object’s prototype. We should always use these methods to access the prototype instead of __proto__
implemented by Chrome or some other browser vendors. Also, Object.create()
method could pass in an object as the prototype of the object to be created.