【Typescript】ts中的命名空间和命名空间块化

Typescript中的命名空间和命名空间块化

命名空间理解

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

命名空间和模块的区别

命名空间:内部模块,主要用于组织代码,避免命名冲突

模块:ts的外部模块简称,侧重于代码的复用,一个模块里面可能有多个命名空间

命名空间的使用

<01单文件使用.ts>文件内使用实例

namespace A {
    interface Animal{ 
        name:string;  
        eat():void;
    } 
    export class Dog implements Animal { //要加export才能用,否则联系不上对应的类
        public name:string
        constructor(name:string){
                this.name = name
        }
        eat(){
            console.log(`${this.name} 吃肉骨头`)
        }
    }
    export class Cat implements Animal{
        public name:string
        constructor(name:string){
                this.name = name
        }
        eat(){
                console.log(this.name+'今天想吃憨八哥')
        }
        work(){
                console.log(this.name+'今天的工作是干饭')
        }
    }
}

namespace B {
    interface Animal{ 
        name:string;  
        eat():void;
    }
    export class Dog implements Animal {
        public name:string
        constructor(name:string){
                this.name = name
        }
        eat(){
            console.log(`${this.name} 吃肉骨头`)
        }
    }
    export class Cat implements Animal{
        public name:string
        constructor(name:string){
                this.name = name
        }
        eat(){
                console.log(this.name+'吃鱼')
        }
        work(){
                console.log(this.name+'今天的工作是水群')
        }
    }
}
var c = new B.Cat('小花')
c.eat()				//输出:小花吃鱼
var b = new A.Cat('修勾')
b.eat()				//输出:修勾今天想吃憨八哥

命名空间块化

如果想在另外一个ts文件内使用这个文件内的命名空间
(即在<02其他文件引入命名空间.ts>文件内想使用<01单文件使用.ts>文件的命名空间)

步骤一

就要在<02其他文件引入命名空间.ts>文件内引入

//02其他文件引入命名空间.ts内部
import {A,B} from './dist/01单文件使用.js'
//就是import {你想要引入的命名空间} from '想要引入的命名空间的js文件路径'
var c = new B.Cat('小花')
c.eat()				//输出:小花吃鱼
var b = new A.Cat('修勾')
b.eat()				//输出:修勾今天想吃憨八哥
步骤二

并且要在<01单文件使用.ts>文件内部的命名空间处暴露

export namespace A {
其他和上面一样,唯独在namespace A前面加了export,将其暴露出去
}
export namespace B {
其他和上面一样,唯独在namespace B前面加了export,将其暴露出去
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值