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

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

    No you can't, JavaScript does not support overloading of any kind.

    What you can do is either pass an object which has already been populated with the values into your constructor and then grab the values from the object, but this which duplicates code.

    Or you can create a default constructor and add methods such as initFromUser or setFromForm which then take the respective parameters and setup the objects values, new User().initFormForm(form) looks pretty clean to me.

提交回复
热议问题