javascript: different constructors for same type of object

浪子不回头ぞ 提交于 2019-12-22 05:28:26

问题


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!


回答1:


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;
        ...
    }
}



回答2:


this might help: JavaScript constructor parameter types



来源:https://stackoverflow.com/questions/4919702/javascript-different-constructors-for-same-type-of-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!