9. TS 之命名空间

97 阅读2分钟

一、命名空间 和 模块化的区别

TS中的模块分为 外部模块 和 内部模块

内部模块称为命名空间 , 命名空间用 namespace 关键字来定义, 主要用于组织代码,避免命名冲突

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

模块在自身的作用域里执行,而不是在全局作用域里。 这意味着定义在一个模块里的变量,函数,类等等在模块外部是不可见的,可以通过 export 暴露 再通过 import 引入

一个模块里可以有多个命名空间

二、命名空间定义

命名空间也叫闭包,可以隔绝作用域

定义关键字 - namespace

当希望命名空间中的属性在全局可见,需要使用 export 关键字将其导出,否则变量只在命名空间内可见

三、命名空间例子

1. 在一个模块里调用多个命名空间

// namespace 定义一个名为 A 的单独的空间
namespace A {
    interface Animal{
        name:string;
        eat():void;
    }

    // 外部需要调用的类 需要用 【export】 给 导出 去
    export class Dog implements Animal {
        name: string;
        constructor(name:string) {
            this.name = name;
        }
        eat() {
            return this.name + '吃骨头1'
        }
        
    }
}

// namespace 定义一个名为 V 的单独的空间
namespace V {
    interface Animal{
        name:string;
        eat():void;
    }

    // 外部需要调用的类 需要用 【export】 给 导出 去
    export class Dog implements Animal {
        name: string;
        constructor(name:string) {
            this.name = name;
        }
        eat() {
            return this.name + '吃骨头2'
        }
        
    }
}

let dog1 = new A.Dog('小黑')
console.log(dog1.eat())  // 小黑吃骨头1

let dog2  = new V.Dog('小白')
console.log(dog2.eat())  // 小白吃骨头2

2. 把模块中多个命名空间导入出来

模块中导出多个命名空间 moudle.ts:

// namespace 定义一个名为 A 的单独的空间
export namespace A {
    interface Animal{
        name:string;
        eat():void;
    }

    // 外部需要调用的类 需要用 【export】 给 导出 去
    export class Dog implements Animal {
        name: string;
        constructor(name:string) {
            this.name = name;
        }
        eat() {
            return this.name + '吃骨头1'
        }
        
    }
}

// namespace 定义一个名为 V 的单独的空间
export namespace V {
    interface Animal{
        name:string;
        eat():void;
    }

    // 外部需要调用的类 需要用 【export】 给 导出 去
    export class Dog implements Animal {
        name: string;
        constructor(name:string) {
            this.name = name;
        }
        eat() {
            return this.name + '吃骨头2'
        }
        
    }
}

导入部分:

// index.ts
import {A , V} from './moudle'

let dog1 = new A.Dog('小小黑')
console.log(dog1.eat())  // 小小黑吃骨头1

let dog2  = new V.Dog('小小白')
console.log(dog2.eat())  // 小小白吃骨头2

注意项 1:命名空间导出的时候需要 export , 命名空间里的属性也要 export

image.png

注意项 2:import 的时候命名空间名字如果不用 as 的时候不能修改, 要和 命名空间的里的名称一致, 如果用 as 重新命名了, 则用命名后的进行调用

image.png