命名空间&声明合并(day06)

命名空间

在js中命名空间能有有效的避免全局污染

  • 在src目录下新建 a.ts b.ts
    • //命名空间和模块不要混用,不要再模块中使用命名空间
    • //命名空间最好在全局环境中使用
namespace Shape {
    const pi = Math.PI
    export function cricle(r: number) {
        return pi * r ** 2
    }
}
//三斜线引用
/// <reference path="a.ts" />

namespace Shape {
    export function square(x: number) {
        return x * x
    }
}

Shape.cricle(1);
Shape.square(1);
  • 先编译 a.ts b.ts

    • tsc ./src/b.ts
  • 在index.html中引入

    • <script src="src/a.js"></script>
    • <script src="src/b.js"></script>
  • 修改 b.ts

    /// <reference path="a.ts" />
    
    namespace Shape {
        export function square(x: number) {
            return x * x
        }
    }
    console.log(Shape.cricle(1))
    console.log(Shape.square(1))
    
    //命名空间和模块不要混用,不要再模块中使用命名空间
    //命名空间最好在全局环境中使用
    
  • 重新编译

名称空间别名问题

//import不是导入的意思~
import cricle = Shape.cricle
console.log(cricle(2))

声明合并

编译器会把程序中多个地方具有相同名称的声明合并为一个声明
可以把程序中散落各处的重名声明合并在一起

接口&函数 的声明合并

  • 在src下新建 merge.ts

    //接口&函数 的声明合并
    interface AA {
        x: number;
        // y: string;
        foo(bar: number): number;       //5
        foo(bar: '1'): number;          //2
    }
    interface AA {
        y: number
        foo(bar: string): string;       //3
        foo(bar: number[]): number[];   //4
        foo(bar: '2'): number;          //1
    }
    let a1: AA = {
        x: 1,
        y: 1,
        foo(bar: any) {
            return bar
        }
    }
    

命名空间与函数 的声明合并

在命名空间中导出的成员不可以重复定义

//src/a.ts
namespace Shape {
    const pi = Math.PI
    export function cricle(r: number) {
        return pi * r ** 2
    }
    // export function square(x: number) {
    //     return x * x
    // }
}
  • 在 merge.ts 中追加

    //命名空间和函数的 声明合并
    function Lib() {
    
    }
    namespace Lib {
        export let version = '1.0'
    }
    console.log(Lib.version) //1.0
    //node:命名空间要放在后面
    

命名空间与类 的声明合并

  • 在 merge.ts 中追加

    // 命名空间与类 的声明合并
    class C2 {
    
    }
    namespace C2 {
        export let state = 1
    }
    console.log(C2.state)
    //node:命名空间要放在后面
    

命名空间与枚举 的声明合并

  • 在 merge.ts 中追加

    //命名空间与枚举 的声明合并
    enum Color {
        Red1,
        Yellow1,
        Bule1
    }
    namespace Color {
        export function mix() { }
    }
    console.log(Color)
    
    //node:命名空间与枚举顺序无要求
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值