Is it possible to create a ES6 class, that assigns a default value to a property if it's not passed in the new method?
class myClass {
constructor(options) {
this.a = typeof options.a !== 'undefined' ? options.a : 'default a value';
this.b = typeof options.b !== 'undefined' ? options.b : 'default b value';
this.c = typeof options.c !== 'undefined' ? options.c : 'default c value';
}
}
var myClassWithValue = new myClass({a:'a value', b: 'b value'});
If I try to do this with this code, compiling with babeljs, I get a TypeError: Cannot set property 'c' of undefined.
Maybe I am not getting how classes work in javascript.
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/