Let's first construct a Person constructor
function Person(name) { this.name=name; } Person.prototype.sayHi=function () { console.log(this.name+",Hello!"); }
Then several inheritance modes are demonstrated by constructing the Student constructor.
1. Inheritance through prototype chain
function Student(age){ this.age=age; }Student.prototype.study1=function () { console.log("I am keen on learning."); }
Student.prototype=new Person("Zhang three ");//Change the prototype pointing to the _proto of Person's instance object__ Student.prototype.study2=function () { console.log("I'm keen on tapping code."); }
Note: Using this method to inherit, adding prototype method in student constructor should pay attention to adding method after changing prototype pointing. Student's way of calling Study1 failed study2 only after Student's instantiation in the above code.
There are shortcomings: when Person instantiates an object, the name attribute is fixed to "Zhang San", and when Student objects are instantiated many times, the inherited name attribute is always "Zhang San";
2. Inheritance by call in the construction of Student function
function Student(age,name) { this.age=age; Person.call(this,name);//Change this pointing by call } Student.prototype.study=function () { console.log("Study"); }
Disadvantage: This method instantiates objects in Student, which can call the original method study of Student, but can not call the method in Person constructor.
3. Combinatorial Inheritance
function Student(age,name) { this.age=age; Person.call(this,name);//adopt call Mode change this point } Student.prototype=new Person();//Changing the Orientation of the Prototype Student.prototype.study=function () { console.log("Study"); }
The problems in the above two ways have been solved.
4. Copy inheritance
var obj1={ name:"Zhang San", age:16, sayHi:function () { console.log(this.name+",Hello!"); } } var obj2={}; for(var key in obj1){ obj2[key]=obj1[key]; } console.dir(obj2); console.dir(obj1);