2024年07月20日 建站教程
Javascript可以实现继承的方法有很多?下面web建站小编给大家简单介绍一下!
原型链继承:利用原型让一个引用类型继承另一个引用类型的属性和方法
function Parent() { ... }
Parent.prototype.method = function() { ... }
function Child() { ... }
Child.prototype = new Parent(); // 继承Parent
let child = new Child();
child.method(); // 可以调用Parent的方法
组合继承:原型链继承与构造函数继承的组合
//使用原型链实现对父类方法的继承,使用构造函数实现对父类属性的继承。
function Parent() { ... }
Parent.prototype.method = function() { ... }
function Child() {
Parent.call(this); // 继承属性
}
Child.prototype = new Parent(); // 继承方法
Child.prototype.constructor = Child;
let child = new Child();
构造函数继承:在子类构造函数中调用父类构造函数
function Parent() { ... }
function Child() {
Parent.call(this); // 继承Parent
}
let child = new Child();
原型式继承:使用一个空对象作为中介,继承另一个对象的属性
let parent = { ... };
let child = Object.create(parent); // 创建对象,parent为原型
child.method = function() { ... }
ES6 的 class 继承:使用 extends 关键字实现继承
class Parent { ... }
class Child extends Parent {
constructor() { ... }
}
let child = new Child();
本文链接:http://so.lmcjl.com/news/8818/