Function overloading in Javascript - Best practices

后端 未结 30 1514
难免孤独
难免孤独 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 03:58

    As this post already contains a lot of different solutions i thought i post another one.

    function onlyUnique(value, index, self) {
        return self.indexOf(value) === index;
    }
    
    function overload() {
       var functions = arguments;
       var nroffunctionsarguments = [arguments.length];
        for (var i = 0; i < arguments.length; i++) {
            nroffunctionsarguments[i] = arguments[i].length;
        }
        var unique = nroffunctionsarguments.filter(onlyUnique);
        if (unique.length === arguments.length) {
            return function () {
                var indexoffunction = nroffunctionsarguments.indexOf(arguments.length);
                return functions[indexoffunction].apply(this, arguments);
            }
        }
        else throw new TypeError("There are multiple functions with the same number of parameters");
    
    }
    

    this can be used as shown below:

    var createVector = overload(
            function (length) {
                return { x: length / 1.414, y: length / 1.414 };
            },
            function (a, b) {
                return { x: a, y: b };
            },
            function (a, b,c) {
                return { x: a, y: b, z:c};
            }
        );
    console.log(createVector(3, 4));
    console.log(createVector(3, 4,5));
    console.log(createVector(7.07));
    

    This solution is not perfect but i only want to demonstrate how it could be done.

提交回复
热议问题