将数组属性添加到此Express.js模型类

为了在Express.js应用程序中成功地将一个string数组的属性添加到JavaScript模型对象中,需要对下面的代码进行哪些特定的更改? AppUser代码被放置在这个GitHub链接的/app/models目录下的一个新的appuser.js文件中。

这里是AppUser类的代码,包括数组的获取者和设置者的占位符,OP要求如何写:

 var method = AppUser.prototype; function AppUser(name) { this._name = name; } method.getName = function() { return this._name; }; //scopes method.getScopes = function() { //return the array of scope string values }; method.setScopes = function(scopes) { //set the new scopes array to be the scopes array for the AppUser instance //if the AppUser instance already has a scopes array, delete it first }; method.addScope = function(scope) { //check to see if the value is already in the array //if not, then add new scope value to array }; method.removeScope = function(scope) { //loop through array, and remove the value when it is found } module.exports = AppUser; 

你可以像这样在ES6中使用类:

 'use strict'; module.exports = class AppUser { constructor(name) { this.name = name; this.scopes = []; } getName() { return this.name; } getScopes() { return this.scopes; } addScope(scope){ if (this.scopes.indexOf(scope) === -1) this.scopes.push(scope); } }