Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

375
Visualizações
How to create and return a private object within a factory function?
const module = (function() {
    let _priv = {a:1};
    return {
        get priv() {return _priv}
    }
})();

let obj = module.priv;

obj.b = 2;

console.log(module.priv); //{a:1, b:2}

Using a factory function (or revealing module pattern in this case), how do I 'get' a private object for reference but have it be immutable?

A more practical example is for a game of tic-tac-toe:

const gameBoard = (function() {
    let _board = (new Array(9)).fill(''); //want it to be immutable from the outside
    const add = (index,mark) => {
        _board[index] = mark;
    }
    const getBoard = () => {return _board}
    
    return {add, getBoard}
})();

I want _board to only be changed by the add() method, but I also want a reference to the board's state in other places in the code. But with this current code the board is exposed and can be altered.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

wouldn't returning a shallow copy be enough?

so instead of

{return _board}

you could do

{return [..._board]}

so in your example that would look like this

const gameBoard = (function() {
    let _board = (new Array(9)).fill(''); //want it to be immutable from the outside
    const add = (index,mark) => {
        _board[index] = mark;
    }
    const getBoard = () => {return [..._board]}
    
    return {add, getBoard, _board}
})();

console.log(gameBoard._board)
console.log(gameBoard.getBoard())
console.log(gameBoard._board === gameBoard.getBoard())

when running the code, you'll see, that the _board and the array returned from getBoard() do not reference the same object ... so changing the array, you'll get from using getBoard() does not have any effect on your actual _board.

And once you've removed _board from the return (I added it to be able to do the comparison outside the function), I don't see a way to gain access to _board from outside the function

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda