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.
export default new Life();instead of all bindings and then importingìmport life from '../Life';getName&setNameof the same instance from one place.