命名空间:
在代码量较大的情况下,为了避免各种变量名相冲突,可以将相识的功能的函数、类、接口等放置在命名空间中。
同java的包、.net的命名空间一样,Typescript的命名空间可以将代码包裹起来,只对外暴露需要访问的对象,命名空间内的对象通过export暴露。
命名空间和模块的区别:
命名空间:内部模块,主要用于组织代码,避免命名冲突。
模块:ts的外部模块的简称,侧重代码的复用,一个模块里可能会有多个命名空间。
在modules中定义一个文件name.ts
export namespace A{ interface Animal{ name:string; eat():void; } export class Dog implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${this.name}在吃狗粮`); } } export class Cat implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${this.name}在吃猫粮`); } } } export namespace B{ interface Animal{ name:string; eat():void; } export class Dog implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${this.name}在吃狗粮`); } } export class Cat implements Animal{ name:string; constructor(theName:string){ this.name = theName } eat(){ console.log(`${this.name}在吃猫粮`); } } }
namespace.js中引入并使用
import {A,B} from './modules/name' var d = new A.Dog('哈士奇小黑'); d.eat() var c = new B.Cat('小花'); c.eat()
export namespace A{
interface Animal{
name:string;
eat():void;
}
export class Dog implements Animal{
name:string;
constructor(theName:string){
this.name = theName
}
eat(){
console.log(`${this.name}在吃狗粮`);
}
}
export class Cat implements Animal{
name:string;
constructor(theName:string){
this.name = theName
}
eat(){
console.log(`${this.name}在吃猫粮`);
}
}
}
export namespace B{
interface Animal{
name:string;
eat():void;
}
export class Dog implements Animal{
name:string;
constructor(theName:string){
this.name = theName
}
eat(){
console.log(`${this.name}在吃狗粮`);
}
}
export class Cat implements Animal{
name:string;
constructor(theName:string){
this.name = theName
}
eat(){
console.log(`${this.name}在吃猫粮`);
}
}
}