简体   繁体   中英

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

You can use closure variables to implement information hiding. Properties are like "public" member variables in other languages, they can be accessed directly; eg 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.

It makes no sense to create a prototype object inside a factory. You should use either

function FooFactory(id) {
  return {
    getIdFromClosure() {
      return id;
    }
  };
}

or

const proto = {
  getId() {
    return this.id;
  }
};
function FooFactory(id) {
  return Object.assign(Object.create(proto), {id});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM