js---继承

一、原型链继承

  • 套路:
  1. 定义父类型的构造函数
  2. 给父类型的原型添加方法
  3. 定义子类型的构造函数
  4. 创建父类型的对象赋值给子类型的原型
  5. 将子类型原型的构造属性设置为子类型
  6. 给子类型原型添加方法
  7. 创建子类型的对象:可以调用父类型的方法
  • 关键:
    子类型的原型为父类型的一个实例对象
// 父类型
function Super() {
	this.superText = 'aaa';
}
Super.prototype.showSuperText = function() {
	console.log(this.superText);
}
// 子类型
function Sub() {
	this.superText = 'bbb';
}
// 子类型的原型为父类型的一个实例对象
Sub.prototype = new Super();
// 让子类型的原型的constructor指向子类型
Sub.prototype.constructor = Sub;
Sub.prototype.showSubText = function() {
	console.log(this.subText);
}

二、借用构造函数继承

  • 套路:
  1. 定义父类型的构造函数
  2. 定义子类型的构造函数
  3. 在子类型构造函数中调用父类型的构造函数
  • 关键:
    在子类型构造函数中通过call()调用父类型构造函数
function Person(name, age) {
	this.name = name;
	this.age = age;
}
function Animal(name, age, sex) {
	Person.call(this, name, age);
	this.sex = sex;
}

三、原型链+借用构造函数的组合继承

  1. 利用原型链实现对父类型对象的方法继承
  2. 利用call()借用父类型构造函数初始化相同属性
function Person(name, age) {
	this.name = name;
	this.age = age;
}
Person.prototype.setName = function(name) {
	this.name = name;
}
function Animal(name, age, sex) {
	Person.call(this, name, age);
	this.sex = sex;
}
Animal.prototype = new Person();
Animal.prototype.constructor = Animal;
Animal.prototype.setSex = function(sex) {
	this.sex = sex;
}

四、ES6类继承

在ES6中引入了类的概念,通过class关键字和extends关键字可以实现类的继承。

class Parent {
  constructor(name) {
    this.name = name;
  }
 
  sayHello() {
    console.log('Hello');
  }
}
 
class Child extends Parent {
  constructor(name, age) {
    super(name); // 必须要有super()
    this.age = age;
  }
}
 
const child = new Child('Child');
console.log(child.name); // Child
child.sayHello(); // Hello
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值