如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)

How to create JavaScript object fields with the default values? (AngularJS model related)

本文关键字:对象 字段 AngularJS 模型 JavaScript 默认值 何创建 创建      更新时间:2023-09-26

我正在尝试为AngularJS应用程序创建模型层。有很好的建议https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc#.3bjnrxun1使用创建对象的功能:

function User(firstName, lastName, role, organisation) {
  // Public properties, assigned to the instance ('this')
  this.firstName = firstName;
  this.lastName = lastName;
  this.role = role;
  this.organisation = organisation;
}

我试图做的是创建没有参数的默认构造函数,例如

 function User() {
  // Public properties, assigned to the instance ('this')
  this.id = getNewId(); //special function that retrieves sequence from database 
  this.firstName = '';
  this.lastName = '';
  this.role = '';
  this.organisation = getDefaultOrganization();
}

我想这很好,应该行得通。但我对编码this.firstName=''感到不安;我很乐意只声明字段,并让JavaScript运行时分配JavaScript类型提供的任何默认值。

如果AngularJS模型框架存在,我会更高兴拥有并使用它,而不是自己创建。我已经看了BreezeJS,但我有两个方面的怀疑。首先,他们的网页有点奇怪(尽管它包含了很多好的文档),并且没有给人留下强大的社区和蓬勃发展的项目的印象。第二,我使用Laravel作为后端,目前似乎没有对Laravel的支持。

您可以在未来使用ecma脚本https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Functions/Default_parameters没有socond功能或

 function User(firstName, lastName, role, organisation) {
 // Public properties, assigned to the instance ('this')
 this.firstName = firstName||"Lorem";
 this.lastName = lastName||"ipsum";
 ...

}