【问题标题】:Why does compiled Angular code use closures instead of classes?为什么编译的 Angular 代码使用闭包而不是类?
【发布时间】:2019-07-18 10:15:57
【问题描述】:

目前正在学习闭包,并注意到 Angular 组件 Typescript 类被编译为闭包函数。在 Javascript 类上使用闭包有什么特别的原因吗?例如从一个全新的项目编译 AppComponent.ts。

var AppComponent = /** @class */ (function () {
   function AppComponent() {
       this.title = 'My App';
   }
   AppComponent.prototype.ngOnInit = function () {
   };
   AppComponent = tslib__WEBPACK_IMPORTED_MODULE_0__["__decorate"]([
    Object(_angular_core__WEBPACK_IMPORTED_MODULE_1__["Component"])({
        selector: 'app-root',
        template: __webpack_require__(/*! ./app.component.html */ "./src/app/app.component.html"),
        styles: [__webpack_require__(/*! ./app.component.scss */ "./src/app/app.component.scss")]
    }),
    tslib__WEBPACK_IMPORTED_MODULE_0__["__metadata"]("design:paramtypes", [])
    ], AppComponent);
    return AppComponent;
}());

我意识到闭包有多种用途,封装就是其中之一,所以当你想要实现的是一个类时,为什么不使用类呢。

谢谢。

【问题讨论】:

标签: javascript angular


【解决方案1】:

因为function 与Internet Explorer 和其他过时的浏览器兼容,但class 关键字不兼容。 class 只能在支持 ES6 的环境中使用。因此,为了兼容性,“类”被转换为立即调用的函数。

【讨论】:

    猜你喜欢
    • 2017-01-11
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 2021-11-11
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多