DEV Community

Discussion on: Emulating "Private" Variables in JavaScript with Closures and Factory Functions

Collapse
 
somedood profile image
Basti Ortiz

Douglas Crockford truly is the legend of JavaScript. I totally agree with that quote.

I bet I would go insane if I needed to write a class for every time I needed to instantiate objects. Just imagine the hassle it would be to pass in an object as an argument to a function if classes were required to instantiate that object.

// Method #1 and Method #2 achieve the exact same thing.

// METHOD #1
class Options {
  constructor(value, isWritable) {
    this.value = value;
    this.writable = isWritable;
  }
}

Object.defineProperty(window, 'dev', new Options('to', false));

// METHOD #2
Object.defineProperty(window, 'dev', {
  value: 'to',
  writable: false
});
Collapse
 
qm3ster profile image
Mihail Malo

That's actually similar to how options work in Rust.
You construct a struct.
If it's big, you often use a builder to not have to construct it all at once.
However, it all works out great in the end, and everyone is ecstatic :/