如何在TypeScript类方法体中引用当前函数?

时间:2017-10-03 23:47:12

标签: typescript dojo

TL; DR:我正在使用命名函数表达式来引用ES5中的当前函数;如何最好地转换为TypeScript方法?

我在很多ES5 / dojo代码中都有以下模式:

"use strict";

declare(SuperClass, {

    //...

    someMethod: function fn() {
        //calls the same method in the superclass
        this.inherited(fn, arguments);

        // ...
    }
});

使用@declare中的dojo-typings装饰器转换为TypeScript(注意:请小心使用;存在很多问题):

@declare(SuperClass)
class SomeClass {

    //...

    someMethod() {
        this.inherited(
            //Is this the only way to directly reference the method?
            SomeClass.prototype.someMethod,
            arguments
        );

        //...
    }
}

我需要在TypeScript中引用someMethod。

  • arguments.callee不是一个选项,因为这是严格模式代码。
  • this.someMethod不是一个选项,因为我需要引用当前正在执行的函数。当前someMethod可以在子类中重写,并使用this.inherited()
  • 从那里调用
  • SomeClass.prototype.someMethod会起作用,但真的有它吗?

理想的解决方案是简单地使用标识符someMethod和TypeScript来发出命名函数表达式。

是否有一种简单的方法可以在不诉诸SomeClass.prototype.method的情况下引用当前函数?

编辑:这里的限制是ES6类语法的结果,而不是TypeScript特有的任何结果。看起来引用非重写类方法(没有额外的legwork)的唯一方法是Class.prototype.method(这里给出了一个很好的概述:stackoverflow.com/a/43694337/163227)。

我想出了一个想法:可以在类外部定义一个变量,然后在类声明后将该方法赋值给变量:

let someMethod;

class SomeClass {

    //...

    someMethod() {
        this.inherited(someMethod, arguments);

        //...
    }
}

someMethod = SomeClass.prototype.someMethod;

0 个答案:

没有答案