js继承-子类继承父类(简单直接)

87 阅读1分钟

什么叫做继承?

const o1={
    name:'o1',
    say(){
      cosnole.log('Hello World');
    }
};
const o2={__proto__:o1};

我们可以说o2继承了o1,o2就可以使用o1上面的属性和方法了。

继承后的东西属于当前对象的原型链上的一部分,当前对象找不到的属性,都会去原型链上面找,直到Object.prototype找不到,再往上遇见null,就返回undefined。

构造函数子类继承父类

function Parent(gender, age) {
    this.gender = gender;
    this.age = age;
}
Parent.prototype.say1 = function () {
    console.log(`我今年${this.age}岁。`);
}


function Child(name, gender, age) {
    this.name = name;
    // 继承父类的属性
    Parent.call(this, gender, age);
    // 继承父类的原型方法
    Object.setPrototypeOf(Child.prototype, Parent.prototype);
    // 继承父类构造函数
    Object.setPrototypeOf(Child, Parent);
}
Child.prototype.say2 = function () {
    console.log(`我名字叫${this.name}。`);
}


/* ======================================== */


const child = new Child('小林', 'man', 18);
console.log("🚀 ~ child:", child);
child.say1(); // 我今年18岁
child.say2(); // 我名字叫小林。

Reflect.construct子类继承父类

Reflect.construct(Child,argsList,Parent);

这样写的好处是,可以通过第三个参数让子类动态继承父类,自定义指定父类。

当然动手能力强的,也可以实现固定父类,动态指定子类。

function Parent(gender, age) {
    this.gender = gender;
    this.age = age;
}
Parent.prototype.say1 = function () {
    console.log(`我今年${this.age}岁。`);
}


function Child(name, ...restArgs) {
    this.name = name;
    if (new.target !== Child) {
        // 继承父类的属性
        new.target.call(this, ...restArgs);
        // 继承父类的原型方法
        Object.setPrototypeOf(Child.prototype, new.target.prototype);
        // 继承父类构造函数
        Object.setPrototypeOf(Child, new.target);
        // 纠正实例对象的[[Prototype]]
        Object.setPrototypeOf(this, Child.prototype);
    }
}
Child.prototype.say2 = function () {
    console.log(`我名字叫${this.name}。`);
}


/* ======================================== */


const child = Reflect.construct(Child, ['小林', 'man', 18], Parent);
console.log("🚀 ~ child:", child);
child.say1(); // 我今年18岁
child.say2(); // 我名字叫小林。

class子类继承父类

class Parent {
    constructor(gender, age) {
        this.gender = gender;
        this.age = age;
    }
    say1() {
        console.log(`我今年${this.age}岁。`);
    }
}


class Child extends Parent {
    constructor(name, ...restArgs) {
        super(...restArgs);
        this.name = name;
    }
    say2() {
        console.log(`我名字叫${this.name}。`);
    }
}


/* ======================================== */


const child = new Child('小林', 'man', 18);
console.log("🚀 ~ child:", child);
child.say1(); // 我今年18岁
child.say2(); // 我名字叫小林。