A shorter class initialisation in ECMAScript 6

前端 未结 3 1484
萌比男神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:28

    Unfortunately, all you can do are simple things like Object.assign, but if you're trying to remove the redundancy of typing all the params twice (once in constructor signature and once in assignment) there isn't much you can do.

    That said, you could do a hack like this. Though I'm not sure the effort and modicum of obfuscation that comes with it is worth it.

    var dependencies = ['param1', 'param2', 'param3'];
    
    class Something {
      constructor(...params) {
        params.forEach((param, index) => this[dependencies[index]] = param);
      }
    }
    
    var something = new Something('foo', 'bar', 'baz');
    // something.param1 === 'foo'
    

    This way you're using a single array of argument names, then using that same array as a reference when creating the properties on your instance of Something. This pattern would work well in an Angular application where you're trying to preserve dependency names through minification by setting the $inject property.

    Something.$inject = dependencies;
    

    PS - Welcome to the redundant hell of classical languages that I thought I got away from when I became a JS developer :P

    Honestly, you should probably just use a classic object literal unless you really need the formality of an actual class.

    Edit: I suppose you could accept an object literal in your constructor if you want the ease of a literal and the formality of an actual class.

    class Something {
      constructor(params) {
        Object.keys(params).forEach((name) => this[name] = params[name]);
      }
    }
    
    var something = new Something({
      param1: 'foo',
      param2: 'bar',
      param3: 'baz'
    });
    

    But now you've just turned a class into a dynamic class that can be instantiated with any properties, kinda like an object literal :P

    Usually I want a class because I want to formalize the object and present a consistent and strictly testable API.

提交回复
热议问题