打字稿:超类构造函数的成员变量

时间:2019-04-28 07:04:42

标签: javascript typescript ecmascript-6

以下代码将提醒undefined

class Parent {
    field: string
    constructor() {
       alert(this.field)
    }
}


class Child extends Parent {
    field = 'child'
}

new Child() #=> undefined

鉴于此,以下警报将按预期发出“子级”

class Parent {
    field: string
    constructor() {
       alert(this.field)
    }
}


class Child extends Parent {
    field = 'child'
    constructor() {
       // without referencing this.field before super(), this.field stays undefiend
       this.field
       super()
    }

}

new Child() #=> 'child'

有什么方法可以满足以下条件?

  1. 像第一个示例一样,省略整个Child的构造函数声明
  2. 抓取子类中的成员变量?

3 个答案:

答案 0 :(得分:2)

我想到的是:

class Parent {
    constructor(public field: string) {
       alert(this.field)
    }
}


class Child extends Parent {
    constructor() {
       super('child');
    }

}

new Child() #=> 'child'

这不符合您的条件,但我觉得它很紧凑。

答案 1 :(得分:2)

好吧,您可以将属性访问权限推迟到微任务:

 class Parent {
   field: string
   constructor() {
     Promise.resolve().then(() => {
        alert(this.field)
     };
   }
 }

但是,虽然可以满足您的条件,但这仍然是错误的方法。如其他答案所示,将field作为构造函数参数传递。

答案 2 :(得分:1)

我敢肯定,无法满足您的条件。

在子类构造函数运行后之后,抓取子类中的成员变量,并且调用super()必须是子类构造函数中的第一条语句。

class Child extends Parent {
    field = 'child';
}
// the above is equal to:
class Child extends Parent {
    constructor(){ super(); this.field = 'child'; }
}

这会导致错误:

class Child extends Parent {
    constructor(){ 
        this.field = 'child'; // ERROR!
        super(); 
    }
}