JS怎么实现继承?
于2023-08-25 22:52:02发布
31
第一种,使用es6的extends直接继承即可。例子
class Person {
// 构造函数
constructor(name) {
this.name = name;
}
showName() {
console.log(this.name);
}
}
class Men extends Person {
// 构造函数
constructor(name, age) {
// 调用父类的构造函数
super(name);
this.age = age;
}
showAge() {
console.log(this.age);
}
}
const men = new Men('tom', 18);
men.showName(); // 继承了Person的showName
men.showAge();
第二种,如果是es5,则使用call或者apply继承属性,使用原型链继承函数
function Person(name) {
this.name = name;
}
// 把函数写在原型链上,不然继承的时候,每个实例对象的函数都不是共享的
Person.prototype.showName = function () {
console.log(this.name);
}
function Men(name, age) {
Person.call(this, name); // 使用call继承属性
this.age = age;
}
Men.prototype.showAge = function () {
console.log(this.age);
}
// 继承Person原型链上的所有函数,函数.prototype实际上是一个数组,存放了该类的所有函数。知道这一点,要继承父类的函数只要通过一个for循环来继承即可。
for (var i in Person.prototype) {
Men.prototype[i] = Person.prototype[i];
}
var men = new Men('tom', 18);
men.showName()
men.showAge();