[1] Prototype chain inheritance
[2] Borrow constructor inheritance
[3] Combinatorial inheritance
[4] Original type inheritance
[5] Parasitic inheritance
[6] Parasitic combinatorial inheritance
function Parent (name) {
this.name = name;
this.colors = ['red'.'blue'.'green'];
}
Parent.prototype.getName = function () {
console.log(this.name)
}
function Child (name, age) {
Parent.call(this, name);
this.age = age;
}
// Three key steps
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
var child1 = new Child('kevin'.'18');
console.log(child1);
Copy the code
Only this inheritance method will be discussed here.
To quote the praise of parasitic combinatorial inheritance from JavaScript Advanced Programming:
The efficiency of this approach is that it calls the Parent constructor only once, and thus avoids creating unnecessary, redundant properties on Parent. Prototype. At the same time, the prototype chain stays the same; Therefore, instanceof and isPrototypeOf can also be used normally. Parasitic combinatorial inheritance is generally considered by developers to be the ideal inheritance paradigm for reference types.
Finally, encapsulate the inheritance method
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = object(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
// When we use:
prototype(Child, Parent);
Copy the code