简体   繁体   中英

Accessing same instance of Javascript class from another file

So I have this JavaScript class "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.

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 .

    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.

When you export Test from the first file, do it as follows:

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. Just remove the new statements from wherever you were creating a Test object before and instead just use the imported instance.

This is a simplified form of the Singleton design pattern which is possible using ES6 imports.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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