Objects and Closures

Here's how objects can be just as good as closures.

function createRunnable(initialValue) {
  return function() {
    console.log(`Ran with initial value of "${initialValue}"`);
  };
}

console.log('With a closure:');
const runnable1 = createRunnable('closure');
runnable1();

// Now with an object.
class Runnable {
  constructor(initialValue) {
    this.initialValue = initialValue;
  }

  run() {
    console.log(`Ran with initial value of "${this.initialValue}"`);
  }
}

const runnable2 = new Runnable('object');
console.log('\nWith an object:');
runnable2.run();
With a closure:
Ran with initial value of "closure"

With an object:
Ran with initial value of "object"

Much in the same way that closures hold onto things by lexically closing over them, objects can store values within their properties. Even so, the object feels more awkward than the closure in this scenario.

The venerable master Qc Na was walking with his student, Anton. Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" Qc Na looked pityingly at his student and replied,

"Foolish pupil - objects are merely a poor man's closures."


So then, here's how closures can be just as good as objects.

// First with an object.
class Person {
  constructor(name) {
    this.name = name;
  }

  setName(name) {
    this.name = name;
  }

  introduceSelf() {
    console.log(`Hi, my name is ${this.name}!`);
  }
}

console.log('With an object:');
const person1 = new Person('Owen');
person1.introduceSelf();
person1.setName('Oliver');
person1.introduceSelf();

// Now with a closure.
function createPerson(name) {
  return function(method, ...params) {
    switch (method) {
    case 'setName':
      name = params[0];
      break;
    case 'introduceSelf':
      console.log(`Hi, my name is ${name}!`);
      break;
    }
  }
}

console.log('\nWith a closure:');
const person2 = createPerson('Claire');
person2('introduceSelf');
person2('setName', 'Chloe');
person2('introduceSelf');
With an object:
Hi, my name is Owen!
Hi, my name is Oliver!

With a closure:
Hi, my name is Claire!
Hi, my name is Chloe!

Within a closure we can change the value of the things we close over, and even do something akin to method dispatch. Even so, the closure feels more awkward than the object in this scenario.

On his next walk with Qc Na, Anton attempted to impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." Qc Na responded by hitting Anton with his stick, saying

"When will you learn? Closures are a poor man's object."

At that moment, Anton became enlightened.