Function overloading in Javascript - Best practices

后端 未结 30 1486
难免孤独
难免孤独 2020-11-22 03:33

What is the best way(s) to fake function overloading in Javascript?

I know it is not possible to overload functions in Javascript as in other languages. If I neede

30条回答
  •  盖世英雄少女心
    2020-11-22 04:06

    You can now do function overloading in ECMAScript 2018 without polyfills, checking var length/type, etc., just use the spread syntax.

    function foo(var1, var2, opts){
      // set default values for parameters
      const defaultOpts = {
        a: [1,2,3],
        b: true,
        c: 0.3289,
        d: "str",
      }
      // merge default and passed-in parameters
      // defaultOpts must go first!
      const mergedOpts = {...defaultOpts, ...opts};
    
      // you can now refer to parameters like b as mergedOpts.b,
      // or just assign mergedOpts.b to b
      console.log(mergedOpts.a);
      console.log(mergedOpts.b);
      console.log(mergedOpts.c);  
      console.log(mergedOpts.d);
    }
    // the parameters you passed in override the default ones
    // all JS types are supported: primitives, objects, arrays, functions, etc.
    let var1, var2="random var";
    foo(var1, var2, {a: [1,2], d: "differentString"});
    
    // parameter values inside foo:
    //a: [1,2]
    //b: true
    //c: 0.3289
    //d: "differentString"

    What is spread syntax?

    The Rest/Spread Properties for ECMAScript proposal (stage 4) adds spread properties to object literals. It copies own enumerable properties from a provided object onto a new object. More on mdn

    Note: spread syntax in object literals doesn't work in Edge and IE and it is an experimental feature. see browser compatability

提交回复
热议问题