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.
There are two types of Class in ES6: parent class/super class: The class extended to create new class are know as a parent class or super class. child/sub classes: The class are newly created are known as child or sub class. Sub class inherit all the properties from parent class except constructor.
Default parameters allow us to initialize functions with default values. A default is used when an argument is either omitted or undefined — meaning null is a valid value. A default parameter can be anything from a number to another function.
Setting JavaScript default parameters for a function In JavaScript, a parameter has a default value of undefined. It means that if you don't pass the arguments into the function, its parameters will have the default values of undefined .
Default parameter in Javascript The default parameter is a way to set default values for function parameters a value is no passed in (ie. it is undefined ). In a function, Ii a parameter is not provided, then its value becomes undefined . In this case, the default value that we specify is applied by the compiler.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With