简体   繁体   中英

Multiple constructor in javascript (overloading)

I have model called Account_Model.js that contains query to create, read, update and delete (CRUD) user account. I need different constructor (to create and update, I need to pass username, fullname, password etc to the constructor, but when I want to delete user account, I only need to pass username).

var connection = require('../config/db.js');

class Account_Model{
    constructor(params){
      this.username = params.username,
      this.fullname = params.fullname,
      this.password = params.password
}
}
getData(){}....

Is this a good practice? Cause when I delete the user, I only pass username in Account_Model instance and left fullname and password null. Thank you

So ES6 does not allow you to have multiple constructors and to be able to overload methods.

Your way of passing an object and only populating certain fields is perfectly valid and is seen in many NPM modules.

You can also look at this example which shows a different way of handling multiple parameters being passed in by checking the length of the passed in parameters: Why doesn't JavaScript ES6 support multi-constructor classes?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM