Variable Does Not Change Inside Factory Function

Asked

Viewed 66 times

1

Good morning.

I was studying a little more about Factory Function and did not understand the reason for the variable img not being altered.

const imgs  = () => {
    let img = [];
    return {
        addImg: (photo) => img = [...img, photo],
        img
    };
};
const images = imgs();
images.addImg('akskaskssk');
images.addImg('aloaloalo');
console.log(images.img); // []

It is possible for the variable to be modified with each method call addImg?

From now on, thank you for your attention!

2 answers

2

I decided to make like one getter, returning the value of variable.

const imgs  = () => {
  let img = [];
  return {
      addImg: (photo) => img = [...img, photo],
      getImg: () => img
  };
};
const images = imgs();
images.addImg('akskaskssk');
images.addImg('aloaloalo');
console.log(images.getImg()); // ["akskaskssk", "aloaloalo"]
  • and what is the practical usefulness of this?

  • @Leocaracciolo is Factory standard. It is usually used in conjunction with an automated resource source.

  • @Augustovasques, I flew kkk, I’m a layman on the subject.

  • @Leocaracciolo, you did not fly. The practical use is not very intuitive because I think it is a simplified example. In this case I believe, my assumption, that this Factory will be used in more complex code that returns lists of HTML elements <img> from a request to a server, the server sends the JSON and the function mounts the tags. The author left this way only to facilitate understanding of the question and eliminating details of the implementation that would not affect the result.

  • @Augustovasques, worth the explanation

2


It doesn’t work because it’s a closure, is a function that keeps with itself the lexical environment which defined it.

At the time of its definition, the function referenced by addImg contained in its scope of definition a variable img the reference to an empty array. At each call of this function what the code img = [...img, photo] does just change the internal reference of an empty array to another array, the external references continue pointing to the same empty array.
That is to say, the internal reference is gone and has not been used and the external references continue pointing to the empty array.

What you should do is modify the composition of the array without modifying the references. For this you can use a Array.prototype.splice(). Take the example:

const imgs = () => {
  let img = [];
  return {
    //Modifica o array mantendo a referência.
    addImg: (photo) => img.splice(img.length, null, photo),
    img
  };
};
const images = imgs();
images.addImg('akskaskssk');
images.addImg('aloaloalo');
console.log(images.img);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.