Function overloading in Javascript - Best practices

后端 未结 30 1516
难免孤独
难免孤独 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:01

    Something like this can be done for function overloading.

    function addCSS(el, prop, val) {
      return {
        2: function() {
          // when two arguments are set
          // now prop is an oject
          for (var i in prop) {
              el.style[i] = prop[i];
          }
        },
        3: function() {
          // when three arguments are set
          el.style[prop] = val;
        }
        }[arguments.length]();
    }
    // usage
    var el = document.getElementById("demo");
    addCSS(el, "color", "blue");
    addCSS(el, {
        "backgroundColor": "black",
      "padding": "10px"
    });
    

    Source

提交回复
热议问题