TypeScript 命名空间
Posted wzndkj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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>
以上是关于TypeScript 命名空间的主要内容,如果未能解决你的问题,请参考以下文章