微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – TypeScript – 如何继承类并覆盖lambda方法

我有一个继承的类,并且需要父类具有一个方法,该方法在子类中被重写.从基础构造函数调用方法,并且需要访问实例属性,因此它需要是lambda函数,因此“this”是“_this”.问题是,重写lambda方法对我来说不起作用就像覆盖非lambda一样.这可能吗?如果没有,我想了解原因.

另外,当只从构造函数调用方法时,“this”是否总是与“_t​​his”相同?

class Base {
    protected prop = null;
    constructor() {
        this.init();
        this.initLambda();
    }
    init() {
        console.log("Base init");
    }
    initLambda = () => {
        console.log("Base initLambda");
    }
}
class Derived extends Base {
    constructor() {
        super();
    }
    init() {
        console.log("Derived init");
    }
    initLambda = () => {
        //let x = this.prop;
        console.log("Derived initLambda");
    }
}

输出
派生的init
基础initLambda

解决方法

好吧,你不能拥有那个.
an issue that was opened但它被关闭为“按设计”.

你应该使用常规方法

class Base {
    protected prop = null;

    constructor() {
        this.init();
        this.initLambda();
    }

    init() {
        console.log("Base init");
    }

    initLambda() {
        console.log("Base initLambda");
    }
}

class Derived extends Base {
    constructor() {
        super();
    }

    init() {
        console.log("Derived init");
    }

    initLambda() {
        console.log("Derived initLambda");
    }
}

然后它会工作.

至于保持正确,你总是可以作为箭头函数调用方法

doit() {
    setTimeout(() => this.init(),1);
}

或使用Function.prototype.bind功能

setTimeout(this.init.bind(this));

此外,打字稿编译器生成的这个东西只是对ES5的箭头函数进行polyfil的黑客攻击,但是如果你将目标更改为ES6则它不会使用它.

编辑:

您可以将绑定方法保存为成员:

class Base {
    ...
    public boundInit: () => void;

    constructor() {
        ...
        this.boundInit = this.initLambda.bind(this);
        setTimeout(this.boundInit,500);
    }

...

有了它,当我做新的Derived()时,这就是我得到的:

Derived init Derived initLambda // after 200 millis

原文地址:https://www.jb51.cc/js/158669.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐