2

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.

2
  • You'll need to have the original instance passed as an argument to the function where you want to use it again or you will have to declare the instance variable in a high enough scope that is accessible by any other code that wants to use it. Commented Apr 18, 2017 at 18:18
  • You're probably looking for a singleton: dofactory.com/javascript/singleton-design-pattern Commented Apr 18, 2017 at 18:27

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.