一篇文章盘点面试题js继承优缺点

原型链继承

优点:写法方便简洁,容易理解

缺点:无法向父级传递参数

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('男')

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值