gpt4 book ai didi

javascript - Typescript 类构造函数生成的代码顺序

转载 作者:行者123 更新时间:2023-12-02 23:49:16 26 4
gpt4 key购买 nike

我正在编写一个服务,但在运行它时出现以下错误。有问题的部分是:

import { Configuration } from "./Configuration";
import { BooksApplication } from "./application/BookApplication";
import { PersistenceBookRepository } from "./application/PersistenceBookRepository";
import { DatabaseAccessor } from "./database/DatabaseAccessor";

export class Context {
public readonly configuration: Configuration;

public constructor(configuration: Configuration) {
this.configuration = configuration;
}

private readonly databaseAccessor = new DatabaseAccessor(
this.configuration.databaseConfiguration
);

private readonly bookRepository = new PersistenceBookRepository(
this.databaseAccessor
);

private readonly bookService = new BooksApplication(this.bookRepository);
}

错误:

TypeError: Cannot read property 'databaseConfiguration' of undefined
at new Context (/sandbox/src/Context.ts:14:24)
at Object.<anonymous> (/sandbox/src/index.ts:6:17)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
error Command failed with exit code 1.

我检查了 Typescript 生成的代码,它看起来像这样:

// ...
var Context = (function () {
function Context(configuration) {
this.databaseAccessor = new DatabaseAccessor_1.DatabaseAccessor(this.configuration.databaseConfiguration);
this.bookRepository = new PersistenceBookRepository_1.PersistenceBookRepository(this.databaseAccessor);
this.bookService = new BooksApplication_1.BooksApplication(this.bookRepository);
this.configuration = configuration;
}
return Context;
}());
// ...

如您所见,this.configuration = configuration; 位于末尾,因此 this.databaseAccessor = new DatabaseAccessor_1.DatabaseAccessor(this.configuration.databaseConfiguration); 失败。

我做错了什么或者 Typescript 中有错误吗?

我尝试更改类(class)成员的顺序,但结果相同。

我有一个项目在这里重现了这个问题:https://codesandbox.io/embed/644k5kwr4r

谢谢。

最佳答案

根据spec proposal,这实际上是正确的启动顺序。 1:

When field initializers are evaluated and fields are added to instances:

  • Base class: At the beginning of the constructor execution, even before parameter destructuring.

  • Derived class: Right after super() returns. (The flexibility in how super() can be called has led many implementations to make a separate invisible initialize() method for this case.)

TLDR:类字段首先执行,在构造函数主体之前。

不过,您可以将初始化移至构造函数中。

<小时/>

由于 TS 是 JS 的超集,因此它也必须符合 ES 规范。

关于javascript - Typescript 类构造函数生成的代码顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55713460/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com