Chapter 5: inheritance
- Prototype Chaining and Object.prototype
- Methods inherited from Object.prototype:
hasOwnProperty()
,propertyIsEnumerable()
,isPrototypeOf()
,valueOf()
,toString()
. valueOf
, gets called whenever an operator is used on an object. By default,valueOf()
simply returns the object instance. But the primitive type will override thevalueOf()
method and it will return the string, boolean, and number. The Date Object, will return the epoch time in milliseconds.toString()
, is called as fallback whenevervalueOf()
returns a reference value instead of a primitive value. It is also implicitly called on primitive values whenever js is expecting a string.- Modifying
Object.prototype
, totally forbidden - Object inheritance: We can specify
[[Prototype]]
with the Object.create() method.
var book = {
title: "The Principles of Object-Oriented JavaScript"
};
// is the same as
var book = Object.create(Object.prototype, {
title: {
configurable: true,
enumerable: true,
value: "The Principles of Object-Oriented JavaScript",
writable: true
}
});
We can also set the first parameters to be null.
7. Constructor Inheritance: based on that every function has a prototype
property that can be modified or replaced.
function YourConstructor() {
// initialization
}
// JavaScript engine does this for you behind the scenes
YourConstructor.prototype = Object.create(Object.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: YourConstructor
writable: true
}
});
- An example of using the constructor inheritance:
js Square.prototype = new Rectangle(); Square.prototype.constructor = Square;
- This the same as it show before:
// inherits from Rectangle
function Square(size) {
this.length = size;
this.width = size;
}
Square.prototype = Object.create(Rectangle.prototype, {
constructor: {
configurable: true,
enumerable: true,
value: Square,
writable: true
}
});
Square.prototype.toString = function() {
return "[Square " + this.length + "x" + this.width + "]";
};
- constructor stealing: using the
call
andapply
- Access super-type methods: Father.prototype.method to access the parent methods.