/ / Fügen Sie der Express.js-Modellklasse eine Array-Eigenschaft hinzu - javascript, node.js, express, mean-stack

Fügen Sie dieser Express.js-Modellklasse eine Array-Eigenschaft hinzu - javascript, node.js, express, mean-stack

Welche spezifischen Änderungen müssen im nachstehenden Code vorgenommen werden, um einem JavaScript-Modellobjekt in einer Express.js-App erfolgreich eine Eigenschaft, die ein Array von Strings ist, hinzuzufügen? Das AppUser Code wird in einen neuen eingefügt appuser.js Datei in der /app/models Verzeichnis dieses GitHub-Links.

Hier ist der Code für die AppUser Klasse, einschließlich Platzhalter für die Getter und Setter für das Array, die von diesem OP nach dem Schreiben gefragt werden:

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;

Antworten:

2 für die Antwort № 1

Sie könnten Klasse in ES6 folgendermaßen verwenden:

"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);
}
}