原型链继承
优点:写法方便简洁,容易理解
缺点:无法向父级传递参数
function Person3(name) {
this.name = 'John';
}
Person3.prototype.showName = function() {
console.log('名字是:' + this.name);
}
function Children3() {}
Children3.prototype = new Person3();
Children3.prototype.showHelp = function() {
console.log('哈哈');
}
const c3 = new Children3();
console.log(c3.name)
c3.showName()
c3.showHelp()
借用构造函数继承
优点:解决了原型链实现继承的不能传参的问题和父类的原型共享的问题。
缺点1:借用构造函数的缺点是方法都在构造函数中定义,因此无法实现函数复用。
缺点2:在父类型的原型中定义的方法,对子类型而言也是不可见的,结果所有类型都只能使用构造函数模式。
function Person4(name) {
this.name = name;
}
Person4.prototype.showName = function() {
console.log('名字是:' + this.name);
}
function Children4(name, age) {
this.age = age
Person4.call(this, name);
}
Children4.prototype.showHelp = function() {
console.log(`姓名${this.name},年龄${this.age}`);
}
const c4 = new Children4('Join', 23)
// c4.showName() // c4.showName is not a function
c4.showHelp()
组合式继承
优点:就是解决了原型链继承和借用构造函数继承造成的影响。
缺点:是无论在什么情况下,都会调用两次父类构造函数:一次是在创建子类原型的时候,另一次是在子类构造函数内部
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.info = function (sex = '男') {
console.log(`名字:${this.name},年龄:${this.age},性别:${sex}`)
}
function Children(name, age, money) {
this.money = money
this.salary = function () {
console.log(`工资是:${this.money}`)
}
Person.apply(this, [name, age]) // 不加这个无法传参数
}
// Children.prototype.salary = function () {
// console.log(`工资是:${this.money}`)
// }
Children.prototype = new Person() // 不加这个无法调用父级方法
const c1 = new Children('张三', 23, 28000)
c1.info('女')
c1.salary()
ES6、 class实现继承
class通过extends关键字实现继承, 其实质是先创造出父类的this对象,
然后用子类的构造函数修改this
子类的构造方法中必须调用super方法, 且只有在调用了super() 之后才能使用this,
因为子类的this对象是继承父类的this对象, 然后对其进行加工,
而super方法表示的是父类的构造函数, 用来新建父类的this对象
class Person2 {
constructor(name, age) {
this.name = name
this.age = age
}
info () {
console.log(`名字:${this.name},年龄:${this.age}`)
}
}
class Children2 extends Person2 {
constructor(name, age, money) {
super(name, age)
this.money = money
}
salaryInfo() {
console.log(`工资是:${this.money}`)
}
allInfo(sex) {
console.log(`名字:${this.name},年龄:${this.age},性别:${sex},工资:${this.money}`)
}
}
const c2 = new Children2('李四', 28, 50000)
c2.info()
c2.salaryInfo()
c2.allInfo('男')