2
Class Life {
   constructor(name = 'no name') {
     this.name = name;
   }
   getName() {
     return this.name;
   }
   setName(name = 'no name') {
     this.name = name;
   }
}

const MyLife = new Life();
export { getName, setName } = MyLife;
export default MyLife;

How can I use the same instance of new Life() i.e, MyLife throughout my code?

Things I have tried;

const MyLife = new Life();
export const getName = MyLife.getName.bind(MyLife);
export const setName = MyLife.setName.bind(MyLife);
export default MyLife;

Every time I try to use this in another file i.e, myOther.js

import { setName } from '../path-of-class.js` setName('Luke Skywalker'); // I get undefined.

What am I doing wrong here?

P.S: the class is in another library, I compile it with webpack & then use in another <package>, The class above works fine if used locally within the same <package> but when I try to use from <package-a> to <package-b> I get setName of undefined.

2
  • Idk for sure if there is a difference but have you tried export default new Life(); instead of all bindings and then importing ìmport life from '../Life'; Commented Jul 10, 2019 at 10:27
  • I want to be able use getName & setName of the same instance from one place. Commented Jul 10, 2019 at 12:36

1 Answer 1

1

Try saving your instance of Life into a static variable probably near the class and return it with a static method

class Life {
   static getInstance() {
     if (!Life.instance) {
       Life.instance = new Life();
     }
     return Life.instance;

   }
   constructor(name = 'no name') {
     this.name = name;
   }
   getName() {
     return this.name;
   }
   setName(name = 'no name') {
     this.name = name;
   }
}

Life.instance = null;

export default Life;

in another file:

import Life from 'module';
const myLife = Life.getInstance();

I'm not completely certain how webpack handles the imports. But having a single instance of a class and using it everywhere is a common pattern in object oriented programming (lookup singleton), usually solved by attaching a static variable of the instance to a class and getting it with a static method. This example achieves the same thing by having a static instance and using getInstance() to return it or create one if it wasn't already. This is a classic implementation of this pattern.

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

1 Comment

Can you please explain your code a bit more, as to how it solved the problem & what it is trying to achieve here. =)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.