Javascript:如何在覆盖派生类之前调用​​基类函数?

时间:2018-04-01 06:36:15

标签: javascript es6-class

我正在尝试在JavaScript中使用继承。我想知道如何在派生类中调用基类方法。

我的基类:

class BaseClass {

    constructor (args, kwargs) {

        this.query_params = args
        /* other initial variables in base class */
    }

    retrive () {

        let offset  =   parseInt(getData(this.query_params, 'offset', 0))
        let limit   =   parseInt(getData(this.query_params, 'limit', 20))

        /* extra functionalities */

    }
}

module.exports = BaseClass

我的派生类:

class DerivedClass extends BaseClass {

    constructor (args, kwargs) {
        super(args, kwargs)

        this.model  =   dataBase.ArticleList // using sequelize for database
    }


    retrive () {

        /* functionalities here */
    }


}

module.exports = DerivedClass

我想在DerivedClass中运行任何其他代码之前在DerivedClass中调用BaseClass retrive函数。

我尝试了搜索解决方案,但找不到任何解决方案。请帮忙。

2 个答案:

答案 0 :(得分:4)

只需在this.retrive();来电后致电super



class BaseClass {
  constructor (args, kwargs) {
    this.query_params = args
    /* other initial variables in base class */
  }
  retrive () {
    console.log('retrive');
  }
}
class DerivedClass extends BaseClass {
    constructor (args, kwargs) {
        super(args, kwargs)
        this.retrive();
        
        console.log('other stuff');
    }
    retrive_list () {
        /* functionalities here */
    }
}
const instant = new DerivedClass();




答案 1 :(得分:3)

您可以像CREATE OR REPLACE FUNCTION ipv6_dec_hex(ip_number numeric) RETURNS character varying AS $BODY$ DECLARE ip int :=null; ip1 character varying := ''; ip2 character varying; BEGIN while(ip_number != 0) LOOP ip = mod(ip_number,16); ip_number = div(ip_number,16); ip1:=ip1||to_hex(ip); raise notice 'ip is %',ip; raise notice 'ip_number is %',ip_number; END LOOP; ip2:=reverse(ip1); return ip2; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100; select ipv6_dec_hex(42541956123769884636017138956568135808) ='20014860486000000000000000008880'; 一样使用super关键字,但它会引用基类对象:

this

另请参阅example on MDN