TypeScript 内部是如何处理封装、继承和数据隐藏的?

How typescript internally handles encapsulation, inheritance and data hiding?

我很好奇探索和理解 typescript 到 es5 的转译过程。我很清楚打字稿如何使用闭包来创建范围和管理继承,但仍然让我感到惊讶的是,打字稿到底是如何实现私有数据成员和封装的,就像在编译的 ES5 中一样,我看不出两者之间有什么区别私有和 public 数据成员范围。打字稿究竟如何在内部处理隐私? 它对原型继承(var __extends)到底做了什么?

这是 typescript 游乐场的 link,我正在试验: https://www.typescriptlang.org/play/#src=class%20Shape%7B%0D%0A%20%20%20%20private%20name%3A%20string%3B%0D%0A%20%20%20%20public%20shapeType%3A%20string%3B%0D%0A%0D%0A%20%20%20%20constructor(name%20%2C%20shapeType)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.name%20%3D%20name%3B%0D%0A%20%20%20%20%20%20%20%20this.shapeType%20%3D%20shapeType%3B%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20%0D%0A%7D%0D%0A%0D%0Aclass%20Triangle%20extends%20Shape%7B%0D%0A%20%20%20%20constructor(name%2C%20shapeType)%20%7B%0D%0A%20%20%20%20%20%20%20%20super(name%20%2C%20shapeType)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D

打字稿:

class Shape{
    private name: string;
    public shapeType: string;

    constructor(name , shapeType) {
        this.name = name;
        this.shapeType = shapeType;
    }

}

class Triangle extends Shape{
    constructor(name, shapeType) {
        super(name , shapeType);
    }
}

已转译的 JS:

var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var Shape = /** @class */ (function () {
    function Shape(name, shapeType) {
        this.name = name;
        this.shapeType = shapeType;
    }
    return Shape;
}());
var Triangle = /** @class */ (function (_super) {
    __extends(Triangle, _super);
    function Triangle(name, shapeType) {
        return _super.call(this, name, shapeType) || this;
    }
    return Triangle;
}(Shape));

成员的隐私只在 typescript 本身内强制执行。所以它们 "private" 只是为了方便起见在打字稿中。在打字稿中,编译器只检查 属性 是否是私有的,但一旦转译,私有 属性 就是一个普通的 属性.

如果你有兴趣在JS中做一些私有的东西,你可以参考Emulating private methods with closures