繁体   English   中英

从另一个类的构造函数调用变量

[英]Call Variable from Constructor of Another Class

假设我有一个.js文件,其中该类已导出,构造函数的构建如下:

 constructor(info) {

    this.info = info;
}

在另一个.js文件中,我想调用该变量并将其更改,并且我希望更改反映在该变量来自的原始.js文件中,因此我很好地导入了该类并将其注入:

@inject(ContactGateway, Router, TestElement)
export class LoginNormal {
  constructor(contactGateway, router, testelement) {
    this.contactGateway = contactGateway;
    this.router = router;
    this.testelement = testelement;
  }

然后在同一个.js文件中的函数中,更改原始变量:

  TestInfo() {
    let testinfo = this.testelement;
    testinfo.info= true;
  }

经过进一步的测试,我发现原始变量根本没有被更改,尝试通过另一个文件中的函数更改原始变量的布尔值时我做错了什么?

提前致谢。

您可能只是注入了一个不同的TestElement实例。 自定义元素通常作用于特定的子容器或视图(取决于上下文)。

如果要确保到处都可以看到相同的实例,并且可以确定只需要一个实例,则可以将该自定义元素的类手动注册为根容器上的单例。

最好只拥有一个单独的服务/状态类,以保留该info属性。 在根容器上将该状态类注册为单例/实例,然后将其注入到TestElementLoginNormal类中。 这是在不同的html资源之间传递信息以进行读取/修改的推荐方法。

这样的事情通常可以解决问题(相应地拆分/移动/重命名):

@inject(ApplicationState)
export class TestElement {
    constructor(state) {
        this.state = state;
    }
}

@inject(ContactGateway, Router, ApplicationState)
export class LoginNormal {
    constructor(contactGateway, router, state) {
        this.contactGateway = contactGateway;
        this.router = router;
        this.state = state;
    }

    TestInfo() {
        this.state.info = true; // will be changed in your TestElement too
    }
}

// the hard way
export class ApplicationState {
    constructor(info) {
        this.info = info;
    }
}

export function configure(config) {
    config.instance(ApplicationState, new ApplicationState(false))
}

// or the easy way (no configure required, but needs parameterless constructor)
@singleton()
export class ApplicationState {
    constructor() {
        this.info = false;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM