ES5类的继承
属性继承
父类.call(this,属性1,属性2,....)
父类.apply(this,[属性1,属性2,....])
原型空间方法继承
通过修改 子类原型中的隐式原型指向父类的显示原型 【原型链原理】---原型链继承(完美)
子类.prototype.__proto__ = 父类.prototype
通过父类的实例化对象 修改子类的隐式原型指向 【原型链原理】---原型链继承
-
缺点:
原型里放了所有的父类属性,性能较低
必须要实例化一个父类对象
子类.prototype.__proto__ = new 父类()
function Student(name,color,w,h,sno,grade){ //属性的继承 Preson.apply(this,[name,color,w,h]) this.sno =sno; this.grade = grade; Student.prototype.study = function(){ return '正在学习' } // 通过父类的实例对象进行继承 Student.prototype.__proto__ = new Preson() }
直接将父类的原型 赋值给 子类的原型 -【缺陷 错误的】
会造成地址共享问题,子类的方法和属性会共享到父类的原型上,有问题!!!!
function Student(name,color,w,h,sno,grade){ //属性的继承 Preson.apply(this,[name,color,w,h]) this.sno =sno; this.grade = grade; Student.prototype.study = function(){ return '正在学习' } Student.prototype.aaa= 1000; } //继承原型空间 Student.prototype = Preson.prototype //修改子类的原型 constructor 指向子类自己 Student.prototype.constructor = Student;
组合式继承
将子类的prototype 指向 父类的实例对象
子类.prototype = new 父类()
function Student(name,color,w,h,sno,grade){ //属性的继承 Preson.apply(this,[name,color,w,h]) this.sno =sno; this.grade = grade; Student.prototype.study = function(){ return '正在学习' } Student.prototype.aaa= 1000; } //组合继承 Student.prototype = new Preson() //需要重新指定 constructor 指向子类自己 Student.prototype.constructor = Student
对象合并继承
Object.assign(子类.prototype,父类.prototype)
function Student(name,color,w,h,sno,grade){ //属性的继承 Preson.apply(this,[name,color,w,h]) this.sno =sno; this.grade = grade; Student.prototype.study = function(){ return '正在学习' } Student.prototype.aaa= 1000; //对象合并继承 Object.assign(Student.prototype,Preson.prototype) }
组合寄生继承【背】 Object.create()
将父类的prototype 和 子类的prototype 合并到一个空对象中 赋值给子类的prototype
子类.prototype = Object.create(父类.prototype) //需要重新指定 constructor 指向子类自己 Student.prototype.constructor = Student
子类.prototype._proto__ = 父类.prototype//组合寄生继承就等同于这个
function Student(name,color,w,h,sno,grade){ //属性的继承 Preson.apply(this,[name,color,w,h]) this.sno =sno; this.grade = grade; Student.prototype.study = function(){ return '正在学习' } Student.prototype.aaa= 1000; } Student.prototype = Object.create(Preson.prototype) //需要重新指定 constructor 指向子类自己 Student.prototype.constructor = Student
-
需要掌握
原型链继承
子类.prototype.__proto__ = 父类.prototype
组合寄生继承
Student.prototype = Object.create(Preson.prototype) //需要重新指定 constructor 指向子类自己 Student.prototype.constructor = Student
对象合并继承
//对象合并继承 Object.assign(Student.prototype,Preson.prototype)