DEV Community

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

Collapse
 
swarupkm profile image
Swarup Kumar Mahapatra

I have been practising Factory Functions for a while in this repo
github.com/swarupkm/practise-js/tr...

The same I have done in Java as typical Object Oriented.

In this link medium.freecodecamp.org/class-vs-f... I found this quotations

I think Class Free Object Oriented Programming is JavaScript’s gift to humanity.
— Douglas Crockford “The Better Parts”

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 :/