命名空间: 在代码较大的情况下,为了避免各种变量命名相互冲突,可将相似功能的函数、类、接口等放着在命名空间内

  1. namespace classNmae{
  2. export class Person{
  3. name: string; //属性 前面省略了public方法
  4. constructor(n:string){
  5. //构造函数 实例化类的时候触发的方法
  6. this.name = n;
  7. }
  8. getName():string{
  9. return this.name;
  10. }
  11. setName(name: string): void{
  12. this.name = name
  13. }
  14. }
  15. var p = new Person('张三');
  16. alert(p.getName()) //张三
  17. p.setName('王五');
  18. alert(p.getName()) //王五
  19. }
  20. //外部调用
  21. var m = new classNmae.Person('命名空间')

命名空间的声明

  1. //utils.ts
  2. namespace Utils{
  3. export interface Iperson{
  4. name: string;
  5. age: number
  6. }
  7. }

通过namespace关键字声明的命名空间, 在命名空间外部需要通过完全限定名访问这些对象, 通常情况下, 声明的命名空间代码和调试代码不在同一个文件中, 因此在其他文件中使用, 注意引入的路径要正确, 此处我们在统计目录中任意一个ts文件中使用我们刚刚定义的命名空间:

  1. // <reference path="utils.ts" />
  2. const me: Utils.Iperson = {
  3. name:'IRIC',
  4. age:23
  5. }
  6. console.log(me)

如上述代码所示,通过 reference 注释引用命名空间,即可通过完全限定名进行访问,我们也可以通过 import 导入模块的形式,引入命名空间:

  1. import './utils'
  2. const me: Utils.IPerson = {
  3. name: 'funlee',
  4. age: 18
  5. }
  6. console.log(me); // {name: 'funlee', age: 18

多文件的命名空间

就像普通的 JS 模块文件可以相互引用一样,包含 namespace 的命名空间文件也可以相互引入,还可以组合成一个更大的命名空间,下面是一个简单的示例,所有文件都在同一目录下,你也可参考官方示例:

  1. //utils.js
  2. namespace Utils {
  3. export interface IAnimal {
  4. name: string;
  5. say(): void;
  6. }
  7. }
  1. //animal.js
  2. export namespace Animal {
  3. export class Dog implements Utils.IAnimal{
  4. name: string;
  5. constructor(theName: string) {
  6. this.name = theName;
  7. }
  8. say() {
  9. console.log(`${this.name}: 汪汪汪`)
  10. }
  11. }
  12. }
  1. //index.js
  2. import {Animal} from './animal';
  3. const he = new Animal.Dog('Jack');
  4. he.say(); // Jack: 汪汪汪