为了更好表达问题,更改一下原描述
class Father{
name: string
constructor(name:string){
this.name = name
console.log(this.name)
}
copy(){
return this.constructor(this.name)
}
}
class Son extends Father {
constructor(name:string){
super(name)
console.log(`i am son of ${name}`)
}
play(){
console.log('play')
}
}
let son = new Son('Bob')
let clone = son.copy()
如果像上面一样调用,编译时就会报需要用new调用constructor,如果将copy改为return new this.constructor检查的时候就直接报Function类型不能使用new,我的问题我继承的子类如何调用copy返回属于自己类的实例,如何能使这段代码正常工作呢?
下面代码改写了copy方法
class Father{
name: string
constructor(name:string){
this.name = name
console.log(this.name)
}
copy(){
const F = this.constructor.prototype.constructor;
return new F(this.name)
}
}
class Son extends Father {
constructor(name:string){
super(name)
console.log(`i am son of ${name}`)
}
play(){
console.log('play')
}
}
let son = new Son('Bob')
let clone = son.copy()
将copy方法中的this.constructor改写为this.constructor.prototype.constructor后,代码正常执行,两个函数应该是一样的,是什么导致这种差异?能给constructor上添加类型签名使得能够直接用前一种方法调用吗?
Test.prototype.constructor本来是个类,它就是Test本身,只能用new调用,看下图