简体   繁体   English

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

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

So I have this JavaScript class "Test".所以我有这个 JavaScript 类“Test”。 I want to make instance of it in Main react component and then later use the same instance in another react component called by some action.我想在 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;

This is beginning of my Main component where I am creating instance of Test这是我创建测试实例的主要组件的开始

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

Now I want to use the same instance of Test which I made above in below but this time use method2 .现在我想使用我在下面创建的相同的 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");
                });
        }

I did it with creating new instance of Test but it felt like not a good way to do this.我通过创建新的 Test 实例来做到这一点,但感觉这不是一个好方法。

When you export Test from the first file, do it as follows:当您从第一个文件导出Test ,请执行以下操作:

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

From there on, whenever you import Test , you'll be actually getting the same instance you created in the export statement.从那时起,无论何时导入Test ,您实际上都会获得在导出语句中创建的相同实例。 Just remove the new statements from wherever you were creating a Test object before and instead just use the imported instance.只需从之前创建Test对象的任何位置删除new语句,而只需使用导入的实例。

This is a simplified form of the Singleton design pattern which is possible using ES6 imports.这是单例设计模式的简化形式,可以使用 ES6 导入。

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

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