Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; } 
like image 434
orshachar Avatar asked Nov 14 '10 19:11

orshachar


People also ask

How do you overload a constructor?

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.

What is constructor in JavaScript object?

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.

How do you call a constructor in JavaScript?

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.


1 Answers

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.

like image 169
Ilya Volodin Avatar answered Sep 23 '22 10:09

Ilya Volodin