A shorter class initialisation in ECMAScript 6

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

    We could create a static method within each class that takes the arguments object and an array of names and returns an object that can be assigned to the new instance using Object.assign.

    Check it out using the Babel REPL.

    class Something {
      static buildArgs (ctx, args, paramNames) {
        let obj = {}
        Array.from(args).forEach(function (arg, i) {
          let name = paramNames[i] || i
          obj[name] = args[i]
        })
        Object.assign(ctx, obj)
      }
    
      constructor () {
        Something.buildArgs(this, arguments, [
          'param1',
          'param2'
        ]);
        console.log(this)
      }
    }
    
    new Something('one', 'two')
    

    Admittedly the addition of a method buildArgs means that this solution is not shorter, however the body of the constructor is and we also have these advantages:

    1. You are only writing the parameter names once.
    2. You are protected against minification.

    The code above accommodates extra arguments (i >= paramNames.length) however we could modify it if this behaviour is undesirable such that these are still parsed, but not assigned to the instance:

    class Something {
      static buildArgs (ctx, args, paramNames) {
        let obj = {instance: {}, extra: {}}
        Array.from(args).forEach(function (arg, i) {
          let name = paramNames[i] || i
          if (name) {
              obj.instance[name] = args[i]
          } else {
              obj.extra[i] = args[i]
          }
        })
        Object.assign(ctx, obj)
      }
    
      constructor () {
        let args = Something.buildArgs(this, arguments, ['param1', 'param2']);
        // Do stuff with `args.extra`
      }
    }
    

    Or ignored altogether:

      static buildArgs (args, paramNames) {
        let obj = {}
        Array.from(args).forEach(function (arg, i) {
          let name = paramNames[i]
          if (name) obj[name] = args[i]
        })
        return obj
      }
    

提交回复
热议问题