1

I have an ES6 Singleton pattern class with its constructor which has got a variable named name in.

class Sample {
  constructor (){
    this.name = ''
  }

  setName = (name)=> {
    this.name = name
  }
  getName = () => {
    return this.name
  }
}
export default new Sample()

This class is used in another class module with import syntax.

// another class module
import Sample from './Sample'

class AnotherClassModule {

  sampleMethod = async () => {
    // some code
    await Sample.setName('First Name')
  }

  //some code
  anotherSampleMethod = async () => {
    // some code
    const name = await Sample.getName()
    // some code
  }
}

As far as I know by the use of this way we have side effect in setName function because it modifies the value of a variable that is out of its scope. Therefore, setName is not a pure function though.

Do we have any solution to change setName to a pure function?

2019
  • 81
  • 1
  • 1
  • 9

0 Answers0