预热--JavaScript 对象的继承
一、基础类
const Person = function (name, age) {
this.name = name
this.age = age
}
Person.prototype = {
getName: function() {
return this.name
},
getAge: function() {
return this.age
}
}
一般我们约定类的首字母大写
二、类继承
类继承是通过原型链继承父类的原型对象
const Student = function() {} Student.prototype = new Person()
缺点:这种方法只能继承对象原型上的方法,不能继承对象构造函数内的属性和方法
三、构造继承
构造继承是通过在方法内调用继承的方法,将继承的属性和方法绑定到当前的方法中
const Student = function(name, age, score){ this.score = score Person.call(this, name, age) }
缺点:这种方法只能将要继承的对象构造内的属性绑定到当前对象内,无法继承对象原型上的方法
四、组合继承
即类继承与构造继承的组合
const Student = function(name, age, score){ this.score = score Person.call(this, name, age) } Student.prototype = new Person()
优点:既能继承对象构造函数内的属性又能继承对象原型上的方法
缺点:父类会调用两次
五、寄生继承
在谈寄生继承前,我们先看一个函数
function inheritObj(obj) { function fn(){} fn.prototype = obj return new fn() }
这个函数本质上还是类继承,但是会用一个中间函数去做承接,而寄生继承就是在这个函数上做一些拓展
function createObj(obj) { // 生成需要继承的对象 const o = inheritObj(obj) // 继承的对象进行拓展 o.prototype.getName = function () {} // 返回继承的对象 retutn o }
寄生继承与类继承的优缺点其实是一样的
六、寄生组合继承
将寄生继承的代码优化
/** * 继承父类原型的方法 * @ params subClass 子类 * @ params superClass 被继承的父类方法 */ function inheritPrototype (subClass, superClass) { // 继承父类的原型对象 const p = new inheritObj(superClass.prototype) // 将实例后错误的方法指向修改 p.constructor = subClass subClass.prototype = p }
使用方法:
const Student = function (name, age, score) { this.score = score Person.call(this, name, age) } inheritPrototype(Student, Person)
优点:比组合继承少执行一次父类函数
缺点:使用中间函数,会有多余的开销
七、多父类继承
在谈多父类继承前,我们先看这样一个函数
const extend = fucntion (target, source){ for (let prototype in source) { target[prototype] = source[prototype] } }
于是我们可以得到继承多个父类的方法
const mix = function() { var target = arguments[0], len = arguments.length, i = 0; while(++i < len) { extend(target, arguments[i]) } }
我们也可以绑定到Object的原型上
Object.prototype.mix = function () { var len = arguments.length, i = -1; while(++i < len) { extend(this, arguments[i]) } }

浙公网安备 33010602011771号