【问题标题】:How to create JavaScript object fields with the default values? (AngularJS model related)如何使用默认值创建 JavaScript 对象字段? (AngularJS 模型相关)
【发布时间】:2016-09-11 13:59:47
【问题描述】:

我正在尝试为 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。

【问题讨论】:

    标签: javascript angularjs model-view-controller mvvm breeze


    【解决方案1】:

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

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

    }

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 2019-10-17
      • 2013-06-03
      • 1970-01-01
      • 2012-09-20
      • 2019-07-13
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多