javascript - 请问js类中如何调用父类的父类的函数?

查看:269
本文介绍了javascript - 请问js类中如何调用父类的父类的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

示例代码如下,请问如何在c类中调用a类中的new函数?

class a {
    _x: number;
    constructor() {
        this._x = 1;
    }
    new(i: number) {
        this._x = i;
    }
}
class b extends a {
    _y: number;
    constructor() {
        super();
        this._y = 2;
    }
    new(i: number) {
        this._y = i;
    }
}
class c extends b {
    _z: number;
    constructor() {
        super();
        this._z = 3;
    }
    new(i: number) {
        super.new(i);
    }
}

上面代码 c类的new函数语句super.new(i) 调用的是 b类中的new函数。b类中的new函数好像把a类中的override了.

解决方案

可以直接调用父类中函数,如下所以

class a {
    constructor() {
        this._x = 1;
    }
    new1(i) {
        this._x = i;
    }
}
class b extends a {
    constructor() {
        super();
        this._y = 2;
    }
    new2(i) {
        this._y = i;
    }
}
class c extends b {
    constructor() {
        super();
        this._z = 3;
    }
    new3(i) {
        super.new(i);
    }
}

var cIns=new c();
console.log(cIns._x)
cIns.new1(4);
console.log(cIns._x)
//输出
//1
//4

如果new名字一样,用下面这种方式

class a {
    constructor() {
        this._x = 1;
    }
    new(i) {
        this._x = i;
    }
}
class b extends a {
    constructor() {
        super();
        this._y = 2;
    }
    new(i) {
        this._y = i;
    }
}
class c extends b {
    constructor() {
        super();
        this._z = 3;
    }
    new(i) {
        super.new(i);
    }
}

var cIns=new c();
console.log(cIns._x)  //1
cIns.__proto__.__proto__.__proto__.new.call(cIns,4)
console.log(cIns._x)//4

这篇关于javascript - 请问js类中如何调用父类的父类的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆