JavaScript inheritance occur between objects is done through prototypes.
JavaScript's built-in approach for inheritance is called prototype chaining, or prototypal inheritance.
The object instances inherit properties from the prototype.
This is the prototype chain: An object inherits from its prototype, while that prototype in turn inherits from its prototype, and so on.
All objects automatically inherit from Object unless you specify otherwise.
All objects inherit from Object.prototype.
Any object defined via an object literal has its [[Prototype]] set to Object.prototype.
var book = {
title : "JavaScript"
};
var prototype = Object.getPrototypeOf(book);
console.log(prototype === Object.prototype); // true
Several of the methods used in the past couple of chapters are defined on Object.prototype and are therefore inherited by all other objects.
Those methods are:
Description | Description |
---|---|
hasOwnProperty() | Determines whether an own property with the given name exists |
propertyIsEnumerable() | Determines whether an own property is enumerable |
isPrototypeOf() | Determines whether the object is the prototype of another |
valueOf() | Returns the value representation of the object |
toString() | Returns a string representation of the object |
These five methods are all from Object.
The valueOf() method gets called whenever an operator is used on an object.
By default, valueOf() returns the object instance.
The primitive wrapper types override valueOf() so that it returns a string for String, a Boolean for Boolean, and a number for Number.
Date object's valueOf() method returns the epoch time in milliseconds.
The following code shows how the valueOf() method is called when used with comparison operator.
var now = new Date();
var earlier = new Date(2010, 1, 1);
console.log(now > earlier); // true
The code above generates the following result.
The toString() method is called whenever valueOf() returns a reference value instead of a primitive value.
It is also implicitly called on primitive values whenever JavaScript is expecting a string.
The following code shows how the toString() is called when
var book = {
title : "JavaScript"
}; /*from ww w . j a va 2 s . c o m*/
var message = "Book = " + book;
console.log(message); // "Book = [object Object]"
var book = {
title : "JavaScript",
toString : function() {
return "[Book " + this.title + "]"
}
};
var message = "Book = " + book;
console.log(message);
The code above generates the following result.
All objects inherit from Object.prototype by default, so changes to Object affect all objects.
Object.prototype.add = function(value) {
return this + value; /*from w w w. j a v a2 s. c o m*/
};
var book = {
title : "Javascript"
};
console.log(book.add(5));
console.log("title".add("end"));
The code above generates the following result.