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

    demo.ts
    class Header {
      constructor() {
        const elem = document.createElement('div');
        elem.innerText = 'This is Header';
        document.body.appendChild(elem);
      }
    }
    
    class Content {
      constructor() {
        const elem = document.createElement('div');
        elem.innerText = 'This is Content';
        document.body.appendChild(elem);
      }
    }
    
    class Footer {
      constructor() {
        const elem = document.createElement('div');
        elem.innerText = 'This is Footer';
        document.body.appendChild(elem);
      }
    }
    
    class Page{
      constructor() {
        new Header();
        new Content();
        new Footer();
      }
    }

    这些代码编译完是这样的

    demo.js
    "use strict";
    var Header = /** @class */ (function () {
      function Header() {
        var elem = document.createElement('div');
        elem.innerText = 'This is Header';
        document.body.appendChild(elem);
      }
      return Header;
    }());
    var Content = /** @class */ (function () {
      function Content() {
        var elem = document.createElement('div');
        elem.innerText = 'This is Content';
        document.body.appendChild(elem);
      }
      return Content;
    }());
    var Footer = /** @class */ (function () {
      function Footer() {
        var elem = document.createElement('div');
        elem.innerText = 'This is Footer';
        document.body.appendChild(elem);
      }
      return Footer;
    }());
    var Page = /** @class */ (function () {
      function Page() {
        new Header();
        new Content();
        new Footer();
      }
      return Page;
    }());
    这些类都变成了一个全局变量,过多的全局变量是不可维护的。这个时候要运用模块化的思想,将这些 class 都包在一个 命名空间里面
    namespace Home{
      class Header {
        constructor() {
          const elem = document.createElement('div');
          elem.innerText = 'This is Header';
          document.body.appendChild(elem);
        }
      }
    
      class Content {
        constructor() {
          const elem = document.createElement('div');
          elem.innerText = 'This is Content';
          document.body.appendChild(elem);
        }
      }
    
      class Footer {
        constructor() {
          const elem = document.createElement('div');
          elem.innerText = 'This is Footer';
          document.body.appendChild(elem);
        }
      }
    
      export class Page{
        constructor() {
          new Header();
          new Content();
          new Footer();
        }
      }
    }
    <script>
      new Home.Page();
    </script>
  • 相关阅读:
    Java后端知识体系
    HashMap底层实现整理
    Java线程池
    Spring Boot+Dubbo 入门
    Go 代码记录(一)
    Servlet 复习
    Spring Cloud(二)Eureka:服务注册与发现
    Spring Cloud (一)概述
    数据结构基础知识
    容器技术-Docker入门
  • 原文地址:https://www.cnblogs.com/wzndkj/p/13171310.html
Copyright © 2011-2022 走看看