- 使用命名空间可以防止全局污染
- 命名空间是可以分布在不同文件中,相同名称的 namespace 共享同一个命名空间。
- 以下面代码为例,
b.ts中可以使用Shape.square()调用到 a.ts 中定义的函数
// a.ts
namespace Shape {
export function square(x: number) {
return x * x
}
}
// b.ts
// 使用以下三斜线指令,可以在编译 b.ts 时将 a.ts 定义的命名空间引入合并
/// <reference path="a.ts" />
namespace Shape {
const pi = Math.PI
export function circlr(r: number) {
return pi * r ** 2
}
}
- 当我们输入
tsc b.ts命令进行编译时,b.ts中的命名空间会编译成一个立即执行函数。 - 两个文件中的全局变量
Shape将会被各自的立即执行函数重复使用,达到 TypeScript 中所述的相同名字的命名空间是共建的目的
// a.js
var Shape;
(function (Shape) {
var pi = Math.PI
function circle(r) {
return pi * Math.pow(r, 2)
}
Shape.circle = circle
})(Shape || (Shape = {}))
// b.js
var Shape;
(function (Shape) {
function square(x) {
return x * x
}
Shape.square = square
})(Shape || (Shape = {}))
注:在 ES6 兴起之后,namespace 事实上已经可以不需要在一个模块化的系统中使用到。