Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Classes Default Value

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.

like image 745
Leonardo Alves Avatar asked Jul 10 '15 13:07

Leonardo Alves


People also ask

What are classes in ES6?

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.

Why will you use default parameters in ES6?

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.

What is default value of VAR in JavaScript?

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 .

Can you assign the default values to a function parameters?

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.


1 Answers

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/

like image 101
Jaromanda X Avatar answered Sep 28 '22 19:09

Jaromanda X