JS as a weakly typed language, inheritance is also one of its larger functions
First define a parent class
// 定义一个教师类function Teacher (name) { // 属性 this.name = name || ‘Jack‘; // 实例方法 this.study= function(){ console.log(this.name + ‘正在学习!‘); }}
One: the way of inheritance
1, prototype chain inheritance: Prototype An instance of the parent class as a child class
function Student(){ }
Student.prototype = new Teacher();
Student.prototype.name = ‘john‘;
Test
Student();
Console.log (Student.name);
2, construct Inheritance (call,apply) uses the constructor of the parent class to enhance an instance of the subclass, equivalent to copying the instance property of the parent class to the subclass
function Student (name) {
Teacher.call (this);
this.name = Name | | "Tom"
}
var student = new Student ();
Console.log (Student.name);
3, instance inheritance: Adds a new attribute to the parent class instance returned as a subclass instance
function Student(name){ var instance = new Teacher(); instance.name = name || ‘Tom‘; return instance;}// 测试var student = new Student();console.log(student.name);
4, copy Inheritance
function Student(name){ var teacher= new Teacher(); for(var p in teacher){ Student.prototype[p] = Teacher[p]; } Student.prototype.name = name || ‘Tom‘;}// 测试var student= new Student();console.log(student.name);
5,组合继承 (通过调用父类的构造,继承父类的属性并保留传参的优点,然后通过将父类实例作为子类原型,实现函数复用
function Student(name){ Teacher.call(this); this.name = name || ‘Tom‘;}Student.prototype = new Teacher();// 测试var student = new Student();console.log(student.name);
6, parasitic combination inheritance through the parasitic way, cut off the parent class instance properties, so that when the construction of two times the parent class is called, it will not initialize two instance methods/properties, avoid the disadvantage of combination inheritance
function Student(name){ Teacher.call(this); this.name = name || ‘Tom‘;}(function(){ // 创建一个没有实例方法的类 var Super = function(){}; Super.prototype = Teacher.prototype; //将实例作为子类的原型 Student.prototype = new Super();})();// 测试var student = new Student();console.log(student.name);
JS Implementation inheritance