2010-11-14 32 views
36

¿Puedo hacer algo como ?:¿Cómo sobrecargar el constructor de un objeto en JS (Javascript)?

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

Respuesta

34

No se puede hacer que, desde JavaScript no es un lenguaje fuertemente tipado no va a ver una diferencia entre la forma y nombre de usuario. Se pueden crear múltiples funciones como createUserFromForm(form) y createUserFromUserInfo(userName, password,...) o usted podría tratar de usar un constructor singular sin argumentos especificados y luego usar argumentos colección para comprobar la entrada y decidir qué hacer.

6

No, no puede, JavaScript no soporta la sobrecarga de ningún tipo.

Lo que puede hacer es pasar un objeto que ya ha sido poblado con los valores en su constructor y luego tomar los valores del objeto, pero esto duplica el código.

O puede crear un constructor por defecto y añadir métodos tales como initFromUser o setFromForm que entonces tomar los respectivos parámetros de configuración y los valores de los objetos, new User().initFormForm(form) ve bastante limpio para mí.

20

me gusta la respuesta Ilya Volodins y pensé que iba a añadir esto como un ejemplo:

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

Probablemente hay maneras más agradables de hacer esto, pero esto sólo un ejemplo.

5

sobrecarga el constructor o cualquier otra función Javascript contando el número de argumentos:

function FooString() 
{ if(arguments.length>0) 
    { this.str=arguments[0]; 
     return; 
    } 
    this.str=""; 
} 

var s1=new FooString; 
var s2=new FooString("hello world"); 

También puede establecer los argumentos por defecto mediante la detección de la cantidad de argumentos que faltan.

0

Se puede simular fácilmente métodos sobrecargados y constructores que utilizan una combinación de cadenas JSON y el comando typeof. Consulte el siguiente ejemplo: el atributo val se forma a partir del tipo de datos que ingresan:

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; 
Cuestiones relacionadas