ES6 Classes Default Value
Object.assign works for me as well
class RenderProperties {
constructor(options = {}){
Object.assign(this, {
fill : false,
fillStyle : 'rgba(0, 255, 0, 0.5)',
lineWidth : 1,
strokeStyle : '#00FF00'
}, options);
}
}
If you're going to use ES6, why not use all of ES6, i.e. default values for parameters and destructuring assignment
class myClass {
constructor({a = 'default a value', b = 'default b value', c = 'default c value'} = {a:'default option a', b:'default option b', c:'default option c'}) {
this.a = a;
this.b = b;
this.c = c;
}
}
var v = new myClass({a:'a value', b: 'b value'});
console.log(v.toSource());
var w = new myClass();
console.log(w.toSource());
http://www.es6fiddle.net/ibxq6qcx/
edit: also tested and confirmed to run on https://babeljs.io/repl/
If you would like to have some properties default but some not you can use also use spread operator (work as same as Object.assign answer)
const defaults = {someDefault: true};
class SomeClass {
constructor(config) {
this.config = {...defaults, ...config};
}
}