First, the prototype chain (default)
function person () {};
function Student () {};
Student.prototype = new Person ();
Student.prototype.constructor = Student;
Cons: 1, how to do the argument? 2. The instance property of new person is the prototype attribute of student.
Second, borrowing the constructor function
function person (name) {this.name = name;}
function Student (name, Klass) {Person.call (this, name); This.klass = Klass;}
Advantages: The communication has been done. Disadvantages: How inheritance is inherited?
Third, combinatorial inheritance (prototype chain + borrowing constructors)
1 functionPerson (name) {2 This. Name =name;3 }4 5 functionStudent (name, Klass) {6Person.call ( This, name);7 This. Klass =Klass;8 }9 TenStudent.prototype =NewPerson (); OneStudent.prototype.constructor = Student;
There are drawbacks: 1. The instance property of new person is a prototype attribute of Student 2 the person constructor was called two times, inefficient
Iv. Temporary constructors
1 functionPerson (name) {2 This. Name =name;3 }4 5 functionStudent (name, Klass) {6Person.call ( This, name);7 This. Klass =Klass;8 }9 Ten(function(){ One varF =function(){}; AF.prototype =Person.prototype; -Student.prototype =NewF (); -Student.prototype.constructor =Student; the})();
It looks good ~ ~
But why does JavaScript have to be a type of inheritance pinch
Here's the point,
Prototype inheritance
Student.prototype = Object.create (Person.prototype);
Student.prototype.constructor = Student;
Prototype chain, chain up: New Student ()-----> Student.prototype----->person.prototype-----> Object.prototype
Put your heart, my heart, string a string, a string of lucky grass, string a concentric circle ~ ~
Object.create Polyfill
if (typeof object.create!== ' function ') { function(o) { var function() {}; = o; return New F (); }}
Additional, inheritance is implemented by copying properties
1 functionExtenddeep (parent, child) {2 vari;3Child = Child | | {};4 for(Iinchparent) {5 if(Parent.hasownproperty (i)) {6 if(typeofParent[i] = = = ' object '){7Child[i] = (Object.prototype.toString.call (parent[i]) = = = ' [Object Array] ')? [] : {};8 Extenddeep (Parent[i], child[i]);9}Else{TenChild[i] =Parent[i]; One } A } - } - returnChild ; the}
Inheritance in JavaScript