2017-02-21 59 views
0

Angular 2 guide Dependency Injection(在第一章爲什麼依賴注入?)有一些奇怪的代碼行。他們工作,但我不知道爲什麼。您還可以在https://angular.io/resources/live-examples/dependency-injection/ts/eplnkr.html上找到正在運行的示例。Angular 2指南中的奇怪的手稿繼承教程DI

在文件car.ts類引擎類汽車被聲明爲:

export class Engine { 
    public cylinders = 4; 
} 

export class Car { 
    public description = 'DI'; 

    constructor(public engine: Engine, public tires: Tires) { } 
    ... 
} 

在文件汽車creation.ts類汽車使用。 ...

import { Car, Engine, Tires } from './car'; 

class Engine2 { 
    constructor(public cylinders: number) { } 
} 

export function superCar() { 
    // Super car with 12 cylinders and Flintstone tires. 
    let bigCylinders = 12; 
    let car = new Car(new Engine2(bigCylinders), new Tires()); 
    car.description = 'Super'; 
    return car; 
} 

它在沒有警告或由Typescript編譯器錯誤工作。

奇怪!爲什麼有可能用錯誤的發動機類型來製造汽車?
new Engine2(...)從類Engine2創建一個對象,該類不是從Engine引出的。

此行爲是Typescript的錯誤還是功能?

我期望文件car-creation.ts中的以下幾行代碼。

class Engine2 extends Engine { 
    constructor(public cylinders: number) { 
    super(); 
    } 
} 

......或者......

class Engine2 extends Engine { 
    constructor(cylinders: number) { 
    super(); 
    this.cylinders = cylinders; 
    } 
} 

回答

1

打字稿使用結構打字而非標稱輸入。您可以在主題here中找到更多信息。即使你正在編寫class它不是類繼承意義上的類。這只是用於創建Prototype的語法糖。

class Engine2 { 
    constructor(public cylinders: number) { } 
} 

class Engine { 
    public cylinders = 4; 
} 

即使它們不相互繼承,它們在結構層次上也是相同的。兩者都有public會員cylindersnumber。雖然Engine將始終有4個氣瓶,但您可以用任何數量的氣瓶初始化Engine2

編寫像constructor(public cylinders: number) {}這樣的構造函數是初始化公共成員的語法糖。