0
点赞
收藏
分享

微信扫一扫

TypeScript学习第九篇 - 命名空间


在开发大型项目时,在同一个模块内代码太多可能造成命名冲突,此时就需要使用TypeScript提供的命名空间的功能,命名空间主要用于组织代码,避免命名冲突。

1.  给要导出的代码段添加命名空间名,并将整个命名空间添加导出,同时,在命名空间内的方法也要添加导出;

// 命名空间A
export namespace A{
    interface Animal {
        name: string;
        eat(): void;
    }
    // 使用了命空间后要添加export导出
    export class Dog implements Animal {
        name: string;
        constructor(theName: string) {
            this.name = theName;
        }
        eat() {
            console.log(`${this.name} 在吃狗粮。`);
        }
    }
    // 使用了命空间后要添加export导出
    export class Cat implements Animal {
        name: string;
        constructor(theName: string) {
            this.name = theName;
        }
        eat() {
            console.log(`${this.name} 吃猫粮。`);
        }
    }   

}

// 命名空间B
export namespace B{
    interface Animal {
        name: string;
        eat(): void;
    }
    // 使用了命空间后要添加export导出
    export class Dog implements Animal {
        name: string;
        constructor(theName: string) {
            this.name = theName;
        }
        eat() {
            console.log(`${this.name} 在吃狗粮。`);
        }
    }
    // 使用了命空间后要添加export导出
    export class Cat implements Animal {
        name: string;
        constructor(theName: string) {
            this.name = theName;
        }
        eat() {
            console.log(`${this.name} 在吃猫粮。`);
        }
    }   
}

2. 引入空间名,通过空间名去访里面的方法;

import {A,B} from './modules/animal.js';

var dog=new A.Dog('小黑');
dog.eat();

var cat=new B.Dog('小花');
cat.eat();

举报

相关推荐

0 条评论