在构造函数中使用已实现的成员(打字稿)

Using implemented members in the constructor (typescript)

我发现在实现 class 时,正在实现的成员在构造函数内不可用。我不知道我是否实施错误,或者我是否真的应该采取不同的方法。

abstract class Parent {
  abstract myVar: number;

  constructor() {
    console.log(this.myVar) // Outputs undefined
  }

  f() {
    console.log(this.myVar) // outputs 5
  }
}

class Child extends Parent {
  myVar: number = 5;
}

let myChild = new Child;
myChild.f();

我怎样才能在构造函数中访问这些已实现的成员?

这个:

class Child extends Parent {
    myVar: number = 5;
}

相当于:

class Child extends Parent {
    myVar: number;

    constructor() {
        super();
        this.myVar = 5;
    }
}

因此您首先调用超级构造函数,在其中您试图访问尚未分配的 myVar

从编译后的js也可以看出来:

var Parent = (function () {
    function Parent() {
        console.log(this.myVar);
    }
    Parent.prototype.f = function () {
        console.log(this.myVar);
    };
    return Parent;
}());
var Child = (function (_super) {
    __extends(Child, _super);
    function Child() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.myVar = 5;
        return _this;
    }
    return Child;
}(Parent));

如果您希望能够在 Parent 构造函数中访问 myVar,您可以执行以下操作:

abstract class Parent {
    abstract myVar: number;

    constructor() {
        this.init();
        console.log(this.myVar);
    }

    f() {
        console.log(this.myVar);
    }

    protected abstract init();
}

class Child extends Parent {
    myVar: number;

    protected init() {
        this.myVar = 5;
    }
}

基本 class 构造函数在其自身执行期间将无法看到派生 class 的字段。

您可以改用此模式:

abstract class Parent {
  constructor(public myVar: number) {
    console.log(this.myVar) // Outputs 5
  }

  f() {
    console.log(this.myVar) // outputs 5
  }
}

class Child extends Parent {
    constructor() {
        super(5);
    }
}

let myChild = new Child;
myChild.f();