javascript - A shorter class initialisation in ECMAScript 6 -
every time create class, need same boring procedure:
class { constructor(param1, param2, param3, ...) { this.param1 = param1; this.param2 = param2; this.param3 = param3; ... } }
is there way make more elegant , shorter? use babel, es7 experimental features allowed. maybe decorators can help?
you can use object.assign
:
class { constructor(param1, param2, param3) { object.assign(this, {param1, param2, param3}); } }
it's es2015 (aka es6) feature assigns own enumerable properties of 1 or more source objects target object.
granted, have write arg names twice, @ least it's lot shorter, , if establish idiom, handles when have arguments want on instance , others don't, e.g.:
class { constructor(param1, param2, param3) { object.assign(this, {param1, param3}); // ...do param2, since we're not keeping property... } }
example: (live copy on babel's repl):
class { constructor(param1, param2, param3) { object.assign(this, {param1, param2, param3}); } } let s = new something('a', 'b', 'c'); console.log(s.param1); console.log(s.param2); console.log(s.param3);
output:
b c
Comments
Post a Comment