繁体   English   中英

从另一个文件访问相同的 Javascript 类实例

[英]Accessing same instance of Javascript class from another file

所以我有这个 JavaScript 类“Test”。 我想在 Main react 组件中创建它的实例,然后在另一个由某些操作调用的 react 组件中使用相同的实例。

class Test
    {
        constructor( arg1, arg2 )
        {
            console.log("initialize with " + arg1 + arg2);
    }
        
        method1(input) {
            console.log("Using this in Main component")
        }

        method2(input) {
            console.log("I want to use this in another component but with same instance as Main component is using.")
        }
    
    }
    export default Test;

这是我创建测试实例的主要组件的开始

class Main extends React.Component
{
    constructor(props)
    {
        super(props);
        new Test("arg1", "arg2")
            .then(test => {
                test.method1("input");
            });
    }

现在我想使用我在下面创建的相同的 Test 实例,但这次使用method2

    export default class AccessFromhere extends React.Component {
        constructor()
        {
            super();
            this.access = this.access.bind(this);
        }
        access()
        {
            console.log("How to get same instance of Test from here to use method2 instead.")
  new Test("arg1", "arg2")
                .then(test => {
                    test.method2("input");
                });
        }

我通过创建新的 Test 实例来做到这一点,但感觉这不是一个好方法。

当您从第一个文件导出Test ,请执行以下操作:

export default new Test("arg1", "arg2");

从那时起,无论何时导入Test ,您实际上都会获得在导出语句中创建的相同实例。 只需从之前创建Test对象的任何位置删除new语句,而只需使用导入的实例。

这是单例设计模式的简化形式,可以使用 ES6 导入。

暂无
暂无

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

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