How to overload constructor of an Object in JS (Javascript)?

前端 未结 6 645
小鲜肉
小鲜肉 2021-02-01 01:19

Can I do something like?:

function User(form) {
    this._username = form.username.value;
    this._password = form.password.value;
    this._surname = form.surn         


        
6条回答
  •  抹茶落季
    2021-02-01 02:00

    Overload the constructor or any other Javascript function by counting the number of arguments:

    function FooString()
    {   if(arguments.length>0)
        {   this.str=arguments[0];
            return;
        }
        this.str="";
    }
    
    var s1=new FooString;
    var s2=new FooString("hello world");
    

    You can also set default arguments by detecting how many arguments are missing.

提交回复
热议问题