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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...