本篇将介绍TypeScript的命名空间,并简单说明一下与模块的区别。
在之前的例子里,有如下一段代码,通过修改这段代码来演示命名空间的用法。
1 interface Animal { 2 name: string; 3 eat(): void; 4 } 5 6 class Dog implements Animal { 7 name: string; 8 constructor(theName: string) { 9 this.name = theName; 10 } 11 12 eat() { 13 console.log(`${this.name} 吃狗粮。`); 14 } 15 } 16 17 class Cat implements Animal { 18 name: string; 19 constructor(theName: string) { 20 this.name = theName; 21 } 22 23 eat() { 24 console.log(`${this.name} 吃猫粮。`); 25 } 26 }
一、命名空间的声明
同Java的包、.Net的命名空间一样,TypeScript的命名空间可以将代码包裹起来,只对外暴露需要在外部访问的对象。命名空间内的对象通过export关键字对外暴露。
将上面的例子进行修改
1 namespace Biology { 2 export interface Animal { 3 name: string; 4 eat(): void; 5 } 6 7 export class Dog implements Animal { 8 name: string; 9 constructor(theName: string) { 10 this.name = theName; 11 } 12 13 eat() { 14 console.log(`${this.name} 吃狗粮。`); 15 } 16 } 17 18 export class Cat implements Animal { 19 name: string; 20 constructor(theName: string) { 21 this.name = theName; 22 } 23 24 eat() { 25 console.log(`${this.name} 吃猫粮。`); 26 } 27 } 28 } 29 30 31 let dog: Biology.Animal; 32 dog = new Biology.Dog('狗狗'); 33 dog.eat();
通过namespace关键字声明命名空间,通过export导出需要在外部使用的对象。在命名空间外部需要通过“完全限定名”访问这些对象。
二、命名空间的引用
通常情况下,声明的命名空间代码和调用的代码不在同一个文件里
biology.ts
1 namespace Biology { 2 export interface Animal { 3 name: string; 4 eat(): void; 5 } 6 7 export class Dog implements Animal { 8 name: string; 9 constructor(theName: string) { 10 this.name = theName; 11 } 12 13 eat() { 14 console.log(`${this.name} 吃狗粮。`); 15 } 16 } 17 18 export class Cat implements Animal { 19 name: string; 20 constructor(theName: string) { 21 this.name = theName; 22 } 23 24 eat() { 25 console.log(`${this.name} 吃猫粮。`); 26 } 27 } 28 }