前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >TypeScript学习第九篇 - 命名空间

TypeScript学习第九篇 - 命名空间

作者头像
越陌度阡
发布2020-11-26 14:45:46
2920
发布2020-11-26 14:45:46
举报

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

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

代码语言:javascript
复制
// 命名空间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. 引入空间名,通过空间名去访里面的方法。

代码语言:javascript
复制
import {A,B} from './modules/animal.js';

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

var cat=new B.Dog('小花');
cat.eat();
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/01/11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档