- 原型链继承
- 构造函数继承
- 组合继承
- 原型式继承
- 寄生继承
- 寄生组合式继承
(1)原型链继承 :children.prototype = new father()
优点:构造简单,继承父类得方法、属性等。缺点:构建子类无法向父类构造器传参。
(2) 构造函数继承: 通过call或apply劫持父类得构造函数来继承。father.apply(this,...args)
。优点:可以使用父构造函数传参。缺点:无法使用父类原型链上的属性、方法
(3) 组合继承:结合原型链继承和组合继承。优点:二者优点皆具。缺点:会执行两次构造函数。
(4) 原型式继承:
function getSon(father)
{
function son(){}
son.prototype = father
return son
}
(5) 寄生继承:在原型式继承得继承上扩展内容。补充ES5有一个新的方法Object.create(),这个方法相当于封装了原型式继承。这个方法可以接收两个参数:第一个是新对象的原型对象(可选的),第二个是新对象新增属性。
(6)寄生组合继承
function JiSheng(son,parent) {
var clone = Object.create(parent.prototype);//创建对象
son.prototype = clone; //指定对象
clone.constructor = son; //增强对象
}
核心是创建以一个新对象继承父类对象prototype当作son得原型,同时将该该原型得construct改为son,修复这个原型.
测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 1 原型链继承
console.log('1 原型链继承')
function father1(name) {
this.name = 'Father1'
}
function child1() {
this.age = 19
}
child1.prototype = new father1()
let son1 = new child1()
console.log(son1.name, son1.age) //Father, 19
// 2 构造函数继承
console.log('2 构造函数继承')
function father2(name) {
this.name = name
this.type = 'person'
}
father2.prototype.show = function () {
console.log(this.name)
}
function child2(name) {
father2.call(this, name)
}
let son2 = new child2('son')
console.log(son2.name)
console.log(son2.type)
// son2.show() error!
// 3 组合式继承
console.log('3 组合式继承')
function father3(name) {
this.name = name
this.type = 'person'
}
father3.prototype.show = function () {
console.log(this.name)
}
function child3(name) {
father3.call(this, name)
}
child3.prototype = new father3()
let son3 = new child3('son3')
console.log(son3)
son3.show()
// 4 原型式继承
console.log('4 原型式继承')
var father4 = {
type: 'perosn',
name: 'father'
}
function getSon(obj) {
function son() {}
son.prototype = obj
return new son()
}
let son4 = getSon(father4)
console.log(son4.name, son4.type)
// 5 寄生继承
console.log('5 寄生继承')
function jiShen1(obj) {
let son = getSon(obj)
son.sayHi = function () {
console.log(`Hello i'm ${this.name}`)
}
return son
}
let son5 = jiShen1(father4)
console.log(son5.name, son5.type)
son5.sayHi()
// 6 寄生组合继承
console.log('6 寄生组合继承')
function father6(name) {
this.name = name
this.type = 'preson'
}
father6.prototype.sayHi = function () {
console.log('hello father6')
}
function jiShen2(son, father) {
let obj = Object.create(father.prototype)
son.prototype = obj
obj.construct = son
}
function getSon6(name) {
this.age = 18
father6.call(this, name)
}
jiShen2(getSon6, father6)
let son6 = new getSon6('JACK')
console.log(son6)
son6.sayHi()
</script>
</body>
</html>