继承是面向对象软件技术中的一个重要概念
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