【问题标题】:Public vs Private in Typescript ConstructorsTypescript 构造函数中的公共与私有
【发布时间】:2016-12-03 08:28:19
【问题描述】:

TypeScript 构造函数中的公共成员在类中是公共的,而私有成员是私有的,这对吗?

如果是这样,公共成员和属性之间的有效区别是什么?

假设不同之处在于属性的行为更像 c# 属性(也就是说,可以有与其访问相关联的代码)为什么要公开一个 字段,而没有固有的保护让它成为财产?

【问题讨论】:

标签: typescript constructor private-members public-members


【解决方案1】:

让我们先看看 C# 类,然后我们将其转换为 TypeScript:

public class Car {
    private int _x;
    private int _y;
    public Car(int x, int y)
    {
        this._x = x;
        this._y = y;
    }
}

意味着_x_y不能从类外访问,只能通过构造函数赋值,如果你想在TypeScript中编写相同的代码,它将是:

class Car {
    constructor(private _x: number, private _y: number) {}
}

如果您使用过 TypeScript,您会注意到我们使用 this 关键字来访问这些变量。

如果只是参数,那么在类的构造函数中使用this._xthis._y是什么意思,因为它也会创建成员变量。

这是从上面的 TypeScript 代码生成的 JavaScript 代码:

var Car = (function () {
    function Car(_x, _y) {
        this._x = _x;
        this._y = _y;
    }
    return Car;
})();

this._xthis._y 被移动到另一个函数中,这意味着 Car 对象无法访问它,但您可以启动和分配 new Car(10, 20)

【讨论】:

    【解决方案2】:

    private 创建一个字段,public 创建一个属性。

    这不像 C# 属性,事实上,它之所以成为属性,只是因为它是公共的。没有访问器。

    【讨论】:

    猜你喜欢
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 2010-10-13
    • 2016-01-09
    相关资源
    最近更新 更多