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>

 

posted @ 2020-06-21 07:41  wzndkj  阅读(164)  评论(0编辑  收藏  举报