打字稿:如何在子类中使用super关键字调用在基类中用箭头函数定义的方法? [英] Typescript: How to call method defined with arrow function in base class using super keyword in child class?

查看:91
本文介绍了打字稿:如何在子类中使用super关键字调用在基类中用箭头函数定义的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出

class BaseClass{

  count:number=0;

  public someMethod=():void =>{
      this.count++;
  }
}

class ChildClass extends BaseClass{
  public someMethod=():void=>{
     super.someMethod();
     //Do more work here.
  }
}

我收到错误消息:

只有基类的公共方法可以通过'super'访问 关键字.

Only public methods of the base class are accessible via the 'super' keyword.

@Basarat在此处提供了一些信息,但这似乎是对该语言的真正破解. 打字稿箭头运算符,用于在原型上定义函数

@Basarat provides some information here but this seems like a real hack to the language. typescript arrow operator to define a function on prototype

在保留上下文对"this"的使用时如何做到这一点?

How might this be done while preserving contextual use of 'this'?

我正确使用了箭头功能,还是应该仅将它们用作声明回调之类的方法?

Am I using arrow functions properly or should they really only be used as a method of declaring something like a callback?

推荐答案

为了争辩,假设您

  • 使用胖箭头语法是因为方法是由UI事件或回调(在我的情况下为敲除点击事件)触发的
  • 需要继承以消除UI(或回调)响应者代码中的冗余.

一个最小的(如果不够优雅)的答案是将您的函数分为两个调用,以解决两个问题:

A minimally hackish (if not elegant) answer is to split your function into two calls that address the two issues:

Class A {
    public handleScope = () => {
        return this.handleInheritance();
    }

    public handleInheritance() {
        // do work
    }
}

Class B extends A {
    public handleInheritance() {
         super.handleInheritance() // super works here
         // additional work
    }
}

我是第一个承认加倍功能丑陋"的人,但是恕我直言,它比我见过的其他选项丑陋得多.为了帮助标准化命名,我将单行作用域"函数命名为基本函数的名称(例如myFunction)加上"Scoper"(即myFunctionScoper).这也是IDE友好的,因为当您开始键入可继承方法的名称时,通常会得到Scoper方法作为提示选项.

I'm the first to admit that doubling functions is "ugly", but IMHO a lot less ugly than the other options I've seen. To help standardize naming, I'm naming the one-line "scoping" function the name of the base function (e.g. myFunction) plus "Scoper" (i.e. myFunctionScoper). This is also IDE-friendly because you'll often get the Scoper method as a hinted option when you start to type the name for the inheritable method.

这篇关于打字稿:如何在子类中使用super关键字调用在基类中用箭头函数定义的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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