打字稿从没有此关键字的方法访问类成员

问题描述 投票:0回答:2

我对 Node 和 TypeScript 很陌生,但令我惊讶的是,在实现类时必须指定

this
来访问类成员。例如:

class MyClass {
  private value: string

  constructor(value: string) {
    this.value = value;
  }
    
  getSomething() { return this.value }
}

有没有办法去掉

this
方法中的
getSomething

node.js typescript oop
2个回答
0
投票

根据本文迄今为止提供的评论,尽管其他答案提供了一种在不使用

this
关键字的情况下自动实现类实现的方法,但这不是推荐的做法。

最重要的是,不可能知道使用在父上下文中相对于类实现声明的变量是有意还是无意。此外,强制仅对类进行成员访问会破坏现有代码。

但是,我仍然认为这可以成为一个 TypeScript 功能,用于新项目(仅限类上下文)。如果不小心关闭,很多代码在访问成员时会因为缺少

this
而无法编译。现有代码应该可以正常编译,因为
this
是多余的。所以,使用这样的功能应该是安全的。


-1
投票

抛开删除

this
会导致无法访问同名的全局变量不谈,下面是如何在实现类时避免使用
this

function newMyClass(value: string) {
  function getSomething() { return value }

  // Return members that are supposed to be public.
  return {
    getSomething
  }
}


class MyClass {
  private internal: ReturnType<typeof newMyClass>
  getSomething: typeof this.internal.getSomething

  constructor(value: string) {
    this.internal = newMyClass(value)
    Object.assign(this, this.internal)
  }
}

console.log(new MyClass("abc").getSomething());

您可以在这里测试此代码:TypeScript Playground。唯一的缺点是出现错误:属性“getSomething”没有初始值设定项,并且未在构造函数中明确分配。

在 Node.js 中失去对同名全局变量的访问不应该成为问题,因为它们在模块级别是全局的。来自其他模块的全局变量可以在导入时重命名:

import { value as module1Value } from './module1'

我还用数字而不是字符串做了基准测试。结果要么相似,要么其中一个比另一个快得多。这是基准代码:TypeScript Playground

© www.soinside.com 2019 - 2024. All rights reserved.