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