Inheritance and Prototype Chain
JavaScript is a prototype-based language, which uses prototype to inherit properties from other objects. Let us look at the following example.
function myFunc() {}; myFunc1 = new myFunc; console.log(myFunc1.__proto__===myFunc.prototype);
When we create a new myFunc
using the new
keyword, the JavaScript interpreter will automatically link myFunc1.__proto__
with myFunc.prototype
.
The purpose of prototype chain is to inherit properties from other objects. Let us look at the following example.
function myFunc() { this.prop1 = "test1"; this.prop2 = "test2_1"; }; myFunc.prototype.prop2 = "test2_2"; myFunc.prototype.prop3 = "test3"; myFunc1 = new myFunc; console.log(myFunc1.prop1); console.log(myFunc1.prop2); console.log(myFunc1.prop3);
Different ways of adding to the prototype chain
new
keyword
a = new b()
means that a.__proto__===b.prototype
Object.create
Calling Object.create
will create an object with the prototype as the first argument of the function.
var a = {prop: 'test'}; // a -> Object.prototype -> null var b = Object.create(a); // b -> a -> Object.prototype -> null console.log(b.prop); // 1 (inherited) var c = Object.create(b); // c -> b -> a -> Object.prototype -> null console.log(c.prop);
- Syntax constructs
var obj = {prop: 1}; console.log(obj.__proto__===Object.prototype); var arr = ["1"]; console.log(arr.__proto__===Array.prototype); var f = function() {}; console.log(f.__proto__===Function.prototype);