admin管理员组

文章数量:1287569

is it possible to have more than one constructors for a class in javascript? i.e. one with zero parameters, one with one, one with two, etc...

if so, how?

thanks!

is it possible to have more than one constructors for a class in javascript? i.e. one with zero parameters, one with one, one with two, etc...

if so, how?

thanks!

Share Improve this question edited Feb 7, 2011 at 9:30 Haim Evgi 126k46 gold badges222 silver badges226 bronze badges asked Feb 7, 2011 at 9:29 clampclamp 34k75 gold badges207 silver badges305 bronze badges 2
  • What you want shall be called "polymorphic function-constructor". look on highdots./forums/javascript/… – Haim Evgi Commented Feb 7, 2011 at 9:32
  • Possible duplicate of JavaScript pattern for multiple constructors – Suma Commented Feb 24, 2017 at 9:31
Add a ment  | 

2 Answers 2

Reset to default 9

No, Javascript does not support function overloading.

However, inside every function you have access to an arguments object, which holds all the arguments supplied to the function, declared or not. You can simply look at it and decide what exactly you want to do in your constructor.

Bad, unrefined example:

function Foo() {

    function singleParamConstructor(foo) {
        ...
    }
    function twoParamConstructor(foo, bar) {
        ...
    }

    switch (arguments.length) {
        case 1 :
            singleParamConstructor(arguments[0]);
            break;
        case 2 :
            twoParamConstructor(arguments[0], arguments[1]);
            break;
        ...
    }
}

this might help: JavaScript constructor parameter types

本文标签: javascript different constructors for same type of objectStack Overflow