【发布时间】:2016-09-14 14:26:05
【问题描述】:
以下是来自Angular 2 docs 的一些示例构造函数:
export class AppComponent implements OnInit {
title = 'Tour of heroes';
heroes: Hero[];
selectedHero: Hero;
constructor(private heroService: HeroService) { }
getHeroes() {
this.HeroService.getHeroes().then(heroes => this.heroes = heroes);
}
}
还有……
class Car {
constructor(engine, tires, doors){
this.engine = engine;
this.tires = tires;
this.doors = doors;
}
}
我不明白为什么以及何时在 angular 2 /typescript 中创建 constructor()(我已阅读官方文档,其中他们为依赖注入和服务创建了构造函数)。
【问题讨论】:
-
+1。我很难知道构造函数中应该包含什么(除了“尽可能少”)以及不应该包含什么。我想这是一个更广泛的编程概念,但我的阅读并没有产生任何特别清楚的东西,它以简单的方式描述了构造函数及其用途。
-
嗨 Sarvesh,如果您将代码作为文本插入,对其他人可能会更好。
-
@J.Chomel 我觉得现在更好了:)
-
我已经编辑了帖子以使其更清晰,并使用代码而不是图像作为示例。
标签: typescript angular