命名空间

命名空间是为了解决全局污染问题,在有了ES6模块之后,全局污染就少了很多,但是一些全局类库也是存在的。
命名空间和模块化尽量不要混合使用
命名空间可以用于组织代码,避免文件内命名冲突

  1. // a.ts
  2. namespace Shape {
  3. const pi = Math.PI
  4. // 想要在其他文件使用该命名空间下的方法,需要导出
  5. export function cricle(r: number) {
  6. return pi * r **2
  7. }
  8. }
  9. // b.ts
  10. /// <referene path="a.ts" />
  11. namespace Shape {
  12. export function square(x: number) {
  13. return x * x
  14. }
  15. }
  16. console.log(Shape.cricle(1))
  17. 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对命名空间的保留,实际上是对全局变量的一种兼容。