web前端全系列 教程
1839个小节阅读:2244.2k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
在真实的应用场景中,当在一个文件中代码量过多,不容易阅读和维护的时候,我们可以通过命名空间的方式将一个文件分离为多个文件
我们来观察下面这个例子:
xxxxxxxxxx
interface Animal{
name:string
}
class Cat implements Animal{
name: string
constructor(name:string){
this.name = name;
}
sayHi(){
console.log(this.name)
}
}
class Dog implements Animal{
name: string
constructor(name:string){
this.name = name
}
sayHello(){
console.log(this.name)
}
}
const c = new Cat("猫")
c.sayHi()
const d = new Dog("狗")
d.sayHello()
当应用变得越来越大时,我们需要将代码分离到不同的文件中以便于维护
xxxxxxxxxx
// Animal.ts
namespace AnimalInfo{
export interface Animal{
name:string
}
}
xxxxxxxxxx
// Cat.ts
namespace AnimalInfo{
export class Cat implements Animal{
name: string
constructor(name:string){
this.name = name;
}
sayHi(){
console.log(this.name)
}
}
}
xxxxxxxxxx
// Dog.ts
namespace AnimalInfo{
export class Dog implements Animal{
name: string
constructor(name:string){
this.name = name
}
sayHello(){
console.log(this.name)
}
}
}
xxxxxxxxxx
// index.ts
const c = new AnimalInfo.Cat("猫")
c.sayHi()
const d = new AnimalInfo.Dog("狗")
d.sayHello()
当涉及到多文件时,我们必须确保所有编译后的代码都被加载了。 我们有两种方式
方式一
把所有的输入文件编译为一个输出文件,需要使用 --outFile
标记
xxxxxxxxxx
tsc --outFile demo.js .\Animal.ts .\Cat.ts .\Dog.ts .\index.ts
方式二
我们可以编译每一个文件(默认方式),那么每个源文件都会对应生成一个 JavaScript 文件。 然后,在页面上通过 <script>
标签把所有生成的 JavaScript 文件按正确的顺序引进来
xxxxxxxxxx
<script src="./Animal.js"></script>
<script src="./Cat.js"></script>
<script src="./Dog.js"></script>
<script src="./index.js"></script>
实时效果反馈
1. 在TypeScript中,实现命名空间的关键字是:
A readonly
B implements
C class
D namespace
答案
1=>D