TS作為JS的超集,增加了面向?qū)ο蟮母拍铕腥洌窃诖蟛糠纸坛潭紱]有說清楚怎么在TS實現(xiàn)面向?qū)ο蟮母鞣N形式,內(nèi)部類在抛、接口實現(xiàn)多態(tài)等钟病。這里介紹類的多種實現(xiàn)方式,接口實現(xiàn)霜定,內(nèi)部類實現(xiàn)接口档悠、靜態(tài)內(nèi)部類。
interface AdapterScanListener {
onScan(adapter: String)
}
class ExternalClass {
test() {
//匿名內(nèi)部類使用
this.hello.hello()
//內(nèi)部類使用
let inner = new this.InnerClass()
inner.hi()
//靜態(tài)內(nèi)部類使用
let staticInner = new ExternalClass.StaticInnerClass()
staticInner.hi()
//內(nèi)部類實現(xiàn)interface
let impl = new this.AdapterScanListenerInnerImpl()
impl.onScan('AdapterScanListenerInnerImpl')
}
/**
* 匿名內(nèi)部類實現(xiàn)
*/
hello = {
hello() {
console.log('hello')
}
}
/**
* 內(nèi)部類
*/
InnerClass = class InnerClass {
hi() {
console.log('hi inner class')
}
}
/**
* 靜態(tài)內(nèi)部類
*/
static StaticInnerClass = class InnerClass {
hi() {
console.log('hi static inner class')
}
}
/**
* 內(nèi)部類實現(xiàn)interface
*/
AdapterScanListenerInnerImpl = class Impl implements AdapterScanListener {
onScan(adapter: String) {
console.log(`onScan:${adapter}`)
}
}
}
let classTest = new ExternalClass()
classTest.test()