简体   繁体   中英

Why does compiled Angular code use closures instead of classes?

Learning about closures at the moment and and noticed Angular component Typescript classes get compiled to closure functions. Is there any particular reason for the use of closures over Javascript classes? eg compiled AppComponent.ts from a brand new project.

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;
}());

I realise closures have various uses and encapsulation is one of them, so why not use classes when what you are trying to achieve is a class anyway.

Thanks.

Because a function is compatible with Internet Explorer and other outdated browsers, but the class keyword is not. class can only be used in environments that support ES6. So, for compatibility, "classes" are transformed into immediately invoked functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM