r/backtickbot • • May 23 '21

https://np.reddit.com/r/javascript/comments/nj696a/20_javascript_concepts_you_should_know_as_a/gz5vsqq/

The closure example doesn't show the most powerful thing about closures. You still have access to variables declared in an outer function even after the outer function has returned.

function counterConstructor() {
  let counter = 0;
  
  function up() {
    counter += 1;
    return counter;
  }

  function down() {
    counter -= 1;
    return counter;
  }

  return Object.freeze({ up, down });
}

const counter1 = counterConstructor();
const counter2 = counterConstructor();

counter1.up(); // 1
counter1.up(); // 2
counter1.up(); // 3

counter2.up(); // 1

Closures give you a much more powerful way to create new objects (compared to classes).

const myConstructor = dependencies => spec => {
    const { dep1, dep2 } = dependencies; // dependency inject
    const { memeber1, member2 } = spec; // constructor arguments
    const reuse = otherConstructor(spec); // composition

    const method = () => {
        // has access to dependencies, spec, reuse, method
    };

    return Object.freeze({ 
        method, 
        goodness: reuse.goodness,
    });
};
1 Upvotes

0 comments sorted by