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);