命名空间
命名空间是为了解决全局污染问题,在有了ES6模块之后,全局污染就少了很多,但是一些全局类库也是存在的。
命名空间和模块化尽量不要混合使用
命名空间可以用于组织代码,避免文件内命名冲突
// a.ts
namespace Shape {
const pi = Math.PI
// 想要在其他文件使用该命名空间下的方法,需要导出
export function cricle(r: number) {
return pi * r **2
}
}
// b.ts
/// <referene path="a.ts" />
namespace Shape {
export function square(x: number) {
return x * x
}
}
console.log(Shape.cricle(1))
console.log(Shape.square(1))
使用:需要编译成.js文件,在html中引用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="src/a.js"></script>
<script src="src/b.js"></script>
</body>
</html>
命名空间成员的别名问题
/// <referene path="a.ts" />
namespace Shape {
export function square(x: number) {
return x * x
}
}
console.log(Shape.cricle(1))
console.log(Shape.square(1))
import cicle = Shape.cricle
// 注意这里的import和模块中的import的意义是不一样的
// 直接使用:
console.log(cicle(2))
ts的早期版本中,命名空间也叫内部模块,本质上就是一个闭包。可以用于隔离作用域。随着ES6模块的引入,内部模块已经不再叫了。现在ts对命名空间的保留,实际上是对全局变量的一种兼容。