Can I do something like?:
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; }
Constructors can be overloaded in a similar way as function overloading. Overloaded constructors have the same name (name of the class) but the different number of arguments. Depending upon the number and type of arguments passed, the corresponding constructor is called.
The Object constructor turns the input into an object. Its behavior depends on the input's type. If the value is null or undefined , it will create and return an empty object. Otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.
A constructor is a special function that creates and initializes an object instance of a class. In JavaScript, a constructor gets called when an object is created using the new keyword. The purpose of a constructor is to create a new object and set values for any existing object properties.
You can't do that, since JavaScript is not a strongly typed language it will not see a difference between form and userName. You can create multiple function like createUserFromForm(form)
and createUserFromUserInfo(userName, password,...)
or you could try to use a singular constructor with no arguments specified and then use arguments collection to check the input and decide what to do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With