Search code examples
javascriptv8

Using closures vs this in prototype object literals contained in factory functions


Is it preferable to use closures instead of instance properties? What is the memory overhead in keeping parent scopes alive, compared to passing properties down as instance properties?

const FooFactory = ({ id }) => {
  const proto = {
    getIdFromClosure() {
      return id;
    },
    getId() {
      return this.id;
    }
  };

  return Object.create(proto, { id: { value: id } });
};

const foo = FooFactory({ id: 123 });  
foo.getIdFromClosure(); // 123
foo.getId(); // 123

Solution

  • You can use closure variables to implement information hiding. Properties are like "public" member variables in other languages, they can be accessed directly; e.g. in your example you can use foo.id instead of foo.getId(). A closure variable is not directly accessible from outside the class, so it's like "private" member variables, you have to call a function to access it.

    This is useful if you don't want to make the value visible, or if you want to reserve the ability to change how it's represented.