1
this.options = Object.assign(Object.create(this.defaultOptions), options);

I understand what this code is doing, but what is the purpose of Object.create()? The only benefit I can think of is that you can reference defaultOptions even if you override them. But I can't think of a good reason why that would be useful for 99% of the time.

user1164937
  • 1,979
  • 2
  • 21
  • 29
  • it's a useful tool for a particular job ... if you don't have a nail, I guess you wouldn't know what a hammer is for – Jaromanda X Jun 29 '18 at 03:05

2 Answers2

2

Using Object.create sets the prototype of this.options. It allows you to shadow the properties on defaultOptions on the options property, and lets you revert to the defaultOptions when needed. For example:

const options = { foo: 'foo', bar: 'bar' };
class Something {
  constructor() {
    this.defaultOptions = options; // only a reference
    this.options = Object.assign(Object.create(this.defaultOptions), options);
  }
}
const inst = new Something();
// Change 'foo':
inst.options.foo = 'foo2';
console.log(inst.options.foo);
// Reset 'foo' to default:
delete inst.options.foo;
console.log(inst.options.foo);
// Assign another custom value to 'foo':
inst.options.foo = 'foofoo';
console.log(inst.options.foo);

This same sort of behavior would not be possible without Object.create - once the object was instantiated, if any option was overwritten, the only way to get the default option would be to have a reference to the default option, which couldn't necessarily be relied on:

const options = { foo: 'foo', bar: 'bar' };
class Something {
  constructor(constrOptions) {
    this.defaultOptions = options; // only a reference
    this.options = Object.assign({}, this.defaultOptions, constrOptions);
  }
}
const inst = new Something();
// Change 'foo':
inst.options.foo = 'foo2';
console.log(inst.options.foo);


// Reset 'foo' to default...??
delete inst.options.foo;
// Doesn't work:
console.log(inst.options.foo);


// Assign another custom value to 'foo':
inst.options.foo = 'foofoo';
console.log(inst.options.foo);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Object.create() creates the new object from passes object. I am not sure about your concern over here. But you can surely visit MDN for more details:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create

https://medium.com/@tkssharma/objects-in-javascript-object-assign-deep-copy-64106c9aefab

Using Object.assign and Object.create for inheritance

Sandip Nirmal
  • 2,283
  • 21
  • 24