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
CodePudding user response:
const createPlayer = (name, gameArr = []) => { //