zoukankan      html  css  js  c++  java
  • 07、TypeScript 命名空间

    命名空间

    /*
      命名空间:
        在代码量比较大的情况下,为了避免各种变量命名项冲突,可将相似功能的函数,类,接口等放置到命名空间内
        同 Java 包,.net 的命名空间一样,TypeScript 的命名空间可以将代码包裹起来,只对外暴露需要在外部访问的对象。命名空间内的对象通过 export
      命名空间和模块的区别:
        命名空间:内部模块,主要用于组织代码,避免命名冲突
        模块:ts 的外部模块的简称,侧重代码的复用,一个模块里可能会有多个命名空间
    */
    
    // 声明一个命名空间 A ,A 命名空间中的代码是私有的
    // 我们还可以声明一个命名空间 B ,B 中的变量名称,接口名称等可以与 A 中一致,不会导致命名冲突
    namespace A {
      interface Animal {
        name: string;
    
        eat(): void;
      }
    
      // 命名空间里面的方法默认私有的,如果在外部使用,需要 export
      export class Dog implements Animal {
        name: string;
    
        constructor(name: string) {
          this.name = name;
        }
    
        eat() {
          console.log(`${this.name}吃狗粮`);
        }
      }
    
      export class Cat implements Animal {
        name: string;
    
        constructor(name: string) {
          this.name = name;
        }
    
        eat() {
          console.log('吃老鼠');
        }
      }
    }
    
    // 这里 A 命名空间中的 Dog 必须暴露 export ,否则访问不到 Dog
    var aDog = new A.Dog('A狼狗');
    aDog.eat();
    
    namespace B {
      interface Animal {
        name: string;
    
        eat(): void;
      }
    
      // 命名空间里面的方法默认私有的,如果在外部使用,需要 export
      export class Dog implements Animal {
        name: string;
    
        constructor(name: string) {
          this.name = name;
        }
    
        eat() {
          console.log(`${this.name}吃狗粮`);
        }
      }
    
      export class Cat implements Animal {
        name: string;
    
        constructor(name: string) {
          this.name = name;
        }
    
        eat() {
          console.log('吃老鼠');
        }
      }
    }
    var bDog = new A.Dog('B狼狗');
    bDog.eat();

    命名空间也可以模块化,进行封装,然后 import 使用

  • 相关阅读:
    Some good websites for C++
    Static Class in C#
    js提示后跳转代码集合
    日期格式化函数
    URL伪静态
    正则的一些使用
    提高.net网站的性能
    验证DropDownList的方法
    用C#去除字符串中HTML的格式
    drepdownlist不能动态绑定数据的原因
  • 原文地址:https://www.cnblogs.com/zhangning187/p/mmkjzn187210413.html
Copyright © 2011-2022 走看看