A shorter class initialisation in ECMAScript 6

前端 未结 3 1482
萌比男神i
萌比男神i 2020-12-10 04:37

Every time I create some class, I need to do the same boring procedure:

class Something {
  constructor(param1, param2, param3, ...) {
    this.param1 = para         


        
3条回答
  •  庸人自扰
    2020-12-10 05:13

    You can use Object.assign:

    class Something {
      constructor(param1, param2, param3) {
        Object.assign(this, {param1, param2, param3});
      }
    }
    

    It's an ES2015 (aka ES6) feature that assigns the own enumerable properties of one or more source objects to a target object.

    Granted, you have to write the arg names twice, but at least it's a lot shorter, and if you establish this as your idiom, it handles it well when you have arguments you do want on the instance and others you don't, e.g.:

    class Something {
      constructor(param1, param2, param3) {
        Object.assign(this, {param1, param3});
        // ...do something with param2, since we're not keeping it as a property...
      }
    }
    

    Example: (live copy on Babel's REPL):

    class Something {
      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:

    a
    b
    c
    

提交回复
热议问题