• 9、TypeScript中的命名空间


    命名空间:

      在代码量较大的情况下,为了避免各种变量名相冲突,可以将相识的功能的函数、类、接口等放置在命名空间中。

      同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}在吃猫粮`);
        }
      }
    }
  • 相关阅读:
    php 条件语句
    MySQL笔记整理任务
    MySQL高可用之PXC
    MySQL高可用之MHA
    虚拟机现有网卡为仅主机模式,需要添加第二块网卡实现上网功能
    Shiro学习
    vue环境搭建
    SpringBoot修改日志的默认配置
    springboot的配置文件application.properties详解
    安装MySQL报错Install/Remove of the Service Denied
  • 原文地址:https://www.cnblogs.com/wenshaochang123/p/13552275.html
Copyright © 2020-2023  润新知