JavaScript实现继承

继承是面向对象软件技术中的一个重要概念

js中实现继承主要有以下这些方法

1.ES6的class继承

ES6引入class关键字,可以方便的实现继承

class Parent {
  constructor() {
    this.name = 'Parent';
  }
​
  sayHello() {
    console.log('Hello, I am ' + this.name);
  }
}
​
class Child extends Parent {
  constructor() {
    super();
    this.childProperty = 'Child';
  }
}
​
let child = new Child();
child.sayHello(); // 输出: Hello, I am Child

2.原型链继承

通过将子类的原型指向父类的实例,从而实现继承,这样子类就能访问父类的属性和方法,但这种方法有个缺点,当子类实例修改继承的属性时,会影响到所有的子类实例,因为所有的子类实例使用的是同一个原型对象,内存空间是共享的。

function Parent() {
  this.name = 'Parent';
}
​
Parent.prototype.sayHello = function() {
  console.log('Hello, I am ' + this.name);
}
​
function Child() {
  this.name = 'Child';
}
​
Child.prototype = new Parent();
​
let child = new Child();
child.sayHello(); // 输出: Hello, I am Child

3.构造函数继承

借助call调用Parent函数,实现属性的继承,但是这种方法无法实现继承父类原型链上的方法

function Parent() {
  this.name = 'Parent';
}
​
function Child() {
  Parent.call(this);
  this.childProperty = 'Child';
}
​
var child = new Child();
console.log(child.name); // 输出: Parent

4.组合继承

结合了原型链继承和构造函数继承的优点,使用原型链实现对原型属性和方法的继承使用构造函数实现对实例属性的继承。不会相互影响

function Parent() {
  this.name = 'Parent';
}
​
Parent.prototype.sayHello = function() {
  console.log('Hello, I am ' + this.name);
}
​
function Child() {
  Parent.call(this);
  this.childProperty = 'Child';
}
​
Child.prototype = new Parent();
Child.prototype.constructor = Child;
​
var child = new Child();
var child2 = new Child();
child.sayHello(); // 输出: Hello, I am Child
child.name = 'child'
console.log(child2.name) //输出:Parent

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值