javascriptarraysfunctionobjectiife

When declaring an object using a factory function in a module pattern, I am unable to access an array inside the module


I'm having trouble understanding why I am unable to access the variable 'gameArr' when creating an object using the 'createPlayer' factory function. When I call 'player.copyArr()' inside of the module pattern, it is unable to access 'gameArr', but 'testObj.copyArr()' is able to.

const createPlayer = (name) => {
  let properties = {
      name,
      copyArr(){
        let newArr = gameArr;
        console.log(newArr)
      }
  }

  return player
}

const game = (() => {
  const gameArr = [1,2,3,4,5]

  let player = createPlayer("Fred")

  let testObj = {
    name: "Bob",
    copyArr(){
      let newArr = gameArr;
      console.log(newArr);
    }
  }

  testObj.copyArr();
  player.copyArr();

  return 
})()

I have already found a way to access 'gameArr' by either placing the 'createPlayer' factory function inside of the 'game' module or by adding parameter to the 'copyArr(gameArr)' inside of 'createPlayer'. But I'm still having trouble understanding why the 'player' object was unable to access 'gameArr' inside of 'game' initially.

Thanks


Solution

  • const createPlayer = (name, gameArr = []) => { // 👈 pass gameArr as paramater so the function can work with.
      let properties = {
          name,
          copyArr(){
            let newArr = gameArr;
            console.log(newArr)
          }
      }
    
      return properties; // 👈 return properties. not player.
    }
    
    const game = (() => {
      const gameArr = [1,2,3,4,5]
    
      let player = createPlayer("Fred", gameArr)
    
      let testObj = {
        name: "Bob",
        copyArr(){
          let newArr = gameArr;
          console.log(newArr);
        }
      }
    
      testObj.copyArr();
      player.copyArr();
    
      return 
    })()