打字稿私有二传手公共获取者约定



所以我想要一个不可变的 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中,只有类以大写字母开头,所以这可能也是一个坏主意。

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

到目前为止,普遍的共识是使用下划线。私有变量不会显示在类外部的自动完成中 - 因此您不会在 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 风格的命名约定,因为它将避免根据您调用的是"我们制作的函数"还是"他们制作的函数"来回切换约定。

仅在大小写的情况下避免差异也是史蒂夫麦康奈尔在代码完成中的建议 - 这是反对xX的另一个不好点,以及您在问题中提到的命名约定点。

最新更新