码迷,mamicode.com
首页 > 其他好文 > 详细

TypeScript 命名空间

时间:2020-06-21 10:06:11      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:type   bsp   code   func   cti   use   script   全局变量   fun   

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>

 

TypeScript 命名空间

标签:type   bsp   code   func   cti   use   script   全局变量   fun   

原文地址:https://www.cnblogs.com/wzndkj/p/13171310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!