【问题标题】:Is there a way to minimize class definitions in Javascript? [duplicate]有没有办法最小化 Javascript 中的类定义? [复制]
【发布时间】:2021-02-21 03:24:52
【问题描述】:

我想在我的节点应用程序中使用类,但我想知道是否有办法(比如在打字稿中)最小化类定义,例如:

class Rectangle(

    constructor(height, width){
        this.height = height;
        this.width = width;
    }
)

类似

class Rectangle(

    constructor(height, width){}
)

所以我不需要将构造函数中的值分配给具有完全相同名称的变量。

【问题讨论】:

  • 据我所知,答案是否定的;这只是 TypeScript 的一个特性。
  • @KenY-N 感谢您提供的信息。我读到您可以在 Node 应用程序中使用 TypeScript 类 - 如果不应该避免的话,我可能会尝试在我的 Node 应用程序中使用 TS 类。

标签: javascript node.js typescript class


【解决方案1】:

不,parameter properties 是仅限打字稿的功能。正如您在ts-playground 上的这个示例中所看到的,类似

class Rectangle{
   constructor(private height:number, public width:number){ }
}

被转译成:

"use strict";
class Rectangle {
    constructor(height, width) {
        this.height = height;
        this.width = width;
    }
}

但是,您可以只在 NodeJS 应用程序中使用 TypeScript - 假设您设置了一个构建步骤,将您的 typescript 代码转换/编译为 javascript。或者,您可以使用 ts-node 之类的库来运行您的代码。

【讨论】:

    猜你喜欢
    • 2020-12-27
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多