我从打字稿开始,我遇到了John Papa的教程。他有以下几点:
// TypeScript
class Car {
// Property (public by default)
engine: string;
// Constructor
// (accepts a value so you can initialize engine)
constructor(engine: string) {
this.engine = engine;
}
}
等效的js代码:
// JavaScript
var Car = (function () {
function Car(engine) {
this.engine = engine;
}
return Car;
})();
让我感到困惑。不应该是:
function Car(engine) {
this.engine = engine;
}
我在这里错过了什么吗?
答案 0 :(得分:2)
你是对的,但TypeScript代码看起来像是......
一旦你向你的班级添加一些方法,它就会变得更加明显:
class Car {
engine: Engine;
constructor(engine: Engine) {
this.engine = engine;
}
drive() {
this.engine.start();
}
}
输出JS如下所示:
var Car = (function () {
function Car(engine) {
this.engine = engine;
}
Car.prototype.drive = function () {
this.engine.start();
};
return Car;
}());
正如您所见,TS使用IIFE来包装整个类声明。
这是将所有东西放在一起的好方法。
使用装饰器的另一个例子:
@decorate
class Car {
engine: Engine;
constructor(engine: Engine) {
this.engine = engine;
}
drive() {
this.engine.start();
}
}
输出JS:
var Car = (function () {
function Car(engine) {
this.engine = engine;
}
Car.prototype.drive = function () {
this.engine.start();
};
Car = __decorate([
decorate
], Car);
return Car;
}());