简体   繁体   English

JavaScript中的多个构造函数(超载)

[英]Multiple constructor in javascript (overloading)

I have model called Account_Model.js that contains query to create, read, update and delete (CRUD) user account. 我有一个名为Account_Model.js的模型,其中包含创建,读取,更新和删除(CRUD)用户帐户的查询。 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. 原因是删除用户时,我仅在Account_Model实例中传递用户名,而全名和密码为null。 Thank you 谢谢

So ES6 does not allow you to have multiple constructors and to be able to overload methods. 因此,ES6不允许您具有多个构造函数并不能重载方法。

Your way of passing an object and only populating certain fields is perfectly valid and is seen in many NPM modules. 您传递对象并且仅填充某些字段的方式是完全有效的,并且在许多NPM模块中都可以看到。

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? 您还可以查看该示例,该示例通过检查传入的参数的长度显示了处理传入的多个参数的另一种方式: 为什么JavaScript ES6不支持多构造器类?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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