命名空间: 在代码较大的情况下,为了避免各种变量命名相互冲突,可将相似功能的函数、类、接口等放着在命名空间内
namespace classNmae{export class Person{name: string; //属性 前面省略了public方法constructor(n:string){//构造函数 实例化类的时候触发的方法this.name = n;}getName():string{return this.name;}setName(name: string): void{this.name = name}}var p = new Person('张三');alert(p.getName()) //张三p.setName('王五');alert(p.getName()) //王五}//外部调用var m = new classNmae.Person('命名空间')
命名空间的声明
//utils.tsnamespace Utils{export interface Iperson{name: string;age: number}}
通过namespace关键字声明的命名空间, 在命名空间外部需要通过完全限定名访问这些对象, 通常情况下, 声明的命名空间代码和调试代码不在同一个文件中, 因此在其他文件中使用, 注意引入的路径要正确, 此处我们在统计目录中任意一个ts文件中使用我们刚刚定义的命名空间:
// <reference path="utils.ts" />const me: Utils.Iperson = {name:'IRIC',age:23}console.log(me)
如上述代码所示,通过 reference 注释引用命名空间,即可通过完全限定名进行访问,我们也可以通过 import 导入模块的形式,引入命名空间:
import './utils'const me: Utils.IPerson = {name: 'funlee',age: 18}console.log(me); // {name: 'funlee', age: 18
多文件的命名空间
就像普通的 JS 模块文件可以相互引用一样,包含 namespace 的命名空间文件也可以相互引入,还可以组合成一个更大的命名空间,下面是一个简单的示例,所有文件都在同一目录下,你也可参考官方示例:
//utils.jsnamespace Utils {export interface IAnimal {name: string;say(): void;}}
//animal.jsexport namespace Animal {export class Dog implements Utils.IAnimal{name: string;constructor(theName: string) {this.name = theName;}say() {console.log(`${this.name}: 汪汪汪`)}}}
//index.jsimport {Animal} from './animal';const he = new Animal.Dog('Jack');he.say(); // Jack: 汪汪汪
