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,将其暴露出去
}