【问题标题】:Typescript private setter public getter convention [closed]打字稿私人设置器公共获取器约定[关闭]
【发布时间】:2014-02-10 16:56:40
【问题描述】:

所以我想要一个不可变的 Vector 类。为此,我需要一个用于 x 和 y 坐标的公共 getter 和一个私有 setter,以便我可以在构造函数中实际初始化这些值。

我有几个选项可供选择,所以我想知道哪一个符合惯例。

我可以这样做:

class Vector {
    constructor(private _x: number, private _y: number) { }
    public get x() {
        return this._x;
    }

    public get y() {
        return this._y;
    }
}

但我不知道使用下划线是否是一种常见的做法。这可能是一个问题,因为该名称将在智能感知中可见。

第二个选项可能是

class Vector {
    constructor(private x: number, private y: number) { }
    public get X() {
        return this.x;
    }

    public get Y() {
        return this.y;
    }
}

据我所知,JS 中只有类以大写字母开头,所以这也可能是个坏主意。

处理此问题的首选方法是什么?

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    到目前为止,普遍的共识是使用下划线。私有变量不会在类之外的自动完成中显示 - 因此您不会在 Vector 实例的自动完成中看到 _x_y。您唯一会看到它们的地方是在调用构造函数时,如果这确实有问题,您可以避免自动映射(尽管我更愿意使用自动映射)。

    class Vector {
        private _x: number;
        private _y: number;
    
        constructor(x: number, y: number) { 
            this._x = x;
            this._y = y;
        }
    
        public get x() {
            return this._x;
        }
    
        public get y() {
            return this._y;
        }
    }
    
    var vector = new Vector(1, 2);
    

    目前还没有官方标准 - 但如果有任何与外部代码交互的机会,最好遵循 JavaScript 样式命名约定,因为它可以避免根据您是否调用“来回切换约定”我们创造的功能”或“他们创造的功能”。

    仅在情况下避免差异也是 Steve McConnell 在 Code Complete 中的建议 - 这是针对 xX 的另一个坏点以及您在问题中提到的命名约定点。

    【讨论】:

    • 可能想要将number 类型添加到xy 属性声明中。
    • 不需要 - 类型推断的强大功能知道它们已经是数字了。
    • 嗯 .. 我也这么认为,但 Playground 没有正确推断出它们(我认为编译器也没有正确推断)。
    • 下划线是 Javascript 中的约定,因为 Javascript 没有私有成员。 Typescript 有。
    • 问题是如果不使用下划线,私有变量和getter/setter同名。在 C# 中,这是通过大写公共 getter/setter 来解决的。奇怪的是,打字稿约定建议您不要使用 _underscore。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2014-08-21
    • 2019-03-11
    • 1970-01-01
    • 2016-10-23
    • 2018-05-24
    • 2015-03-05
    相关资源
    最近更新 更多