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

前端 未结 6 644
小鲜肉
小鲜肉 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:01

    You can easily simulate overloaded methods and constructors using a combination of JSON strings and the typeof command. See example below - you the val attribute gets shaped from the type of data coming in:

    function test(vals)
        {
            this.initialise = function (vals) {
    
                if (typeof (vals) == 'undefined')
                {
                    this.value = 10;
                }
                else if (Object.prototype.toString.call(vals) === '[object Array]')
                {
                    this.value = vals[0];
                }
                else if (typeof (vals) === 'object') {
                    if (vals.hasOwnProperty('x')) {
                        this.value = vals.x;
                    }
                    else if (vals.hasOwnProperty('y')) {
                        this.value = vals.y;
                    }
                }
                else {
                    this.value = vals; // e.g. it might be a string or number
                }
    
            }
    
            this.otherMethods = function () {
                // other methods in the class
            }
    
            this.initialise(vals);
        }
    
        var obj1 = test(); // obj1.val = 10;
        var obj2 = test([30, 40, 50]); // obj1.val = 30;
        var obj3 = test({ x: 60, y: 70 }); // obj1.val = 60;
        var obj4 = test({ y: 80 }); // obj1.val = 80;
        var obj5 = test('value'); // obj1.val = 'value';
        var obj6 = test(90); // obj1.val = 90;
    

提交回复
热议问题