代码之家  ›  专栏  ›  技术社区  ›  orshachar

如何在JS(Javascript)中重载对象的构造函数?

  •  41
  • orshachar  · 技术社区  · 14 年前

    我能做点什么吗?:

    function User(form) {
        this._username = form.username.value;
        this._password = form.password.value;
        this._surname = form.surname.value;
        this._lastname = form.lastname.value;
        this._birthdate = form.b_day.value+"-"+form.b_month.value+"-"+form.b_year.value;
        this._avatar = form.avatar;
        this._messages = new Array();
        this._messagesCount=0;
    }
    
    function User(userName,password,surname,lastName,birthdate) {
        this._username = userName;
        this._password = password;
        this._surname = surname;
        this._lastname = lastName;
        this._birthdate = birthdate;
        this._avatar = form.avatar;
        this._messages = new Array();
        this._messagesCount=0;
    }
    
    5 回复  |  直到 13 年前
        1
  •  45
  •   ntalbs    9 年前

    你不能这样做,因为JavaScript不是一种强类型语言,它不会看到表单和用户名之间的区别。您可以创建多个函数,如 createUserFromForm(form) createUserFromUserInfo(userName, password,...) 或者可以尝试使用一个没有指定参数的单一构造函数,然后使用 论据 集合以检查输入并决定要执行的操作。

        2
  •  21
  •   Patrik    13 年前

    我喜欢Ilya Volodins的回答,我想我可以加上一个例子:

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

    可能有更好的方法来做这件事,但这只是一个例子。

        3
  •  8
  •   Ivo Wetzel    14 年前

    不,不行,JavaScript不支持任何类型的重载。

    您可以做的是将已经填充了值的对象传递到构造函数中,然后从对象中获取值,但这会复制代码。

    或者您可以创建一个默认构造函数并添加一些方法,如 initFromUser setFromForm 然后获取相应的参数并设置对象值, new User().initFormForm(form) 在我看来很干净。

        4
  •  5
  •   Robin Rowe    11 年前

    通过计算参数的数量来重载构造函数或任何其他Javascript函数:

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

    还可以通过检测缺少多少参数来设置默认参数。

        5
  •  0
  •   Randhir Rawatlal    9 年前

    可以使用JSON字符串和typeof命令的组合轻松模拟重载方法和构造函数。请参见下面的示例-您可以根据传入的数据类型来确定val属性的形状:

    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;
    
        6
  •  0
  •   Rufat Gulabli    5 年前

    您可以使用下面的ES6特性创建构造函数。

    class Person {
      constructor(name, surname) {
        if (typeof name === "object") {
          this.name = name.name;
          this.surname = name.surname;
        } else {
          this.name = name;
          this.surname = surname;
        }
      }
    }
    
    const person1 = new Person("Rufat", "Gulabli");
    const person2 = new Person({ name: "Rufat", surname: "Gulabli" });
    const person3 = new Person();
    console.log(person1);
    console.log(person2);
    console.log(person3);
    

    打印输出:

    • 人{名:'Rufat',姓:'Gulabli'}
    • 人{名:'Rufat',姓:'Gulabli'}
    • 人{名:未定义,姓:未定义}