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

前端 未结 6 656
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-01 01:55

    I like Ilya Volodins answer and I thought I would add this as an example:

    function foo() {
        var evt = window.event || arguments[1] || arguments.callee.caller.arguments[0];
        var target = evt.target || evt.srcElement;
    
        var options = {};
    
        if (arguments[0]) options = arguments[0];
    
        var default_args = {
            'myNumber'      :   42,
            'myString'      :   'Hello',
            'myBoolean'     :   true
        }
        for (var index in default_args) {
            if (typeof options[index] == "undefined") options[index] = default_args[index];
        }
    
        //Do your thing
    
    }
    
    //then you call it like this
    foo();
    
    //or
    
    foo({'myString' : 'World'});
    
    //or
    
    foo({'myNumber' : 666, 'myString' : 'World', 'myBoolean' : false});
    

    There are probably nicer ways of doing this but this just one example.

提交回复
热议问题