所以我有以下类声明:
abstract class A {
constructor() {
console.log("A.constructor() is called.");
this.foo();
}
abstract foo();
}
abstract class B extends A {}
class C extends B {
private bar = null;
foo() {
console.log("C.foo() is called.");
this.bar = "bar";
}
getBar() {
console.log("C.getBar() is called.");
return this.bar;
}
}
现在,我尝试通过以下操作对此进行调用:
let x = new C();
console.log(x.getBar());
以下是输出:
A.constructor() is called.
C.foo() is called.
C.getBar() is called.
null
我有完全相同的代码,但是在PHP中,它可以正常工作。有人可以解释一下我在想什么吗?
预先感谢, 拉蒙
答案 0 :(得分:1)
您将像上面的代码片段一样将Ts编译为JS,我记下了代码中的几点。
class A {
constructor() {
console.log("A.constructor() is called.");
this.foo(); // 2. Set `this.bar = "bar"` => Ok
// You can check bar value by add a `console.log(this.bar)` here
}
}
class B extends A {
}
class C extends B {
constructor() {
super(...arguments); // 1. A constructor has been call at first
this.bar = null; // 3. `bar` value has been `reset` to `null`
}
foo() {
console.log("C.foo() is called.");
this.bar = "bar";
}
getBar() {
console.log("C.getBar() is called.");
return this.bar;
}
}
let x = new C();
console.log(x.getBar());