Sto lavorando con un'API RESTful e il mio codice Javascript sta effettuando query REST tramite la chiamata $ .ajax() di jQuery.Dichiarazione costante prototipo Javascript
Ho implementato una classe javascript riposo, che vi mostrerò di seguito (molto semplificata):
var Rest = function (baseUrlPath, errorMessageHandler) {
...
};
// Declare HTTP response codes as constants
Rest.prototype.STATUS_OK = 200;
Rest.prototype.STATUS_BAD_REQUEST = 400;
... // other rest methods
Rest.prototype.post = function (params) {
$.ajax({
type: 'POST',
url: params.url,
data: params.data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
beforeSend: this._authorize,
success: params.success,
error: params.error || this._getAjaxErrorHandler(params.errorMessage)
});
};
... // more rest methods
Rest.prototype.executeScenario = function (scenarioRef) {
var self = this;
this.post({
url: 'myurlgoeshere',
data: 'mydatagoeshere',
success: function (data, textStatus, xhr) {
if (xhr.status == 200) {
console.log("everything went ok");
}
},
error: function (xhr, textStatus, errorMsg) {
// TODO: constants
if (404 == xhr.status) {
self.errorMessageHandler("The scenario does not exist or is not currently queued");
} else if (403 == xhr.status) {
self.errorMessageHandler("You are not allowed to execute scenario: " + scenarioRef.displayName);
} else if(423 == xhr.status) {
self.errorMessageHandler("Scenario: " + scenarioRef.displayName + " is already in the queue");
}
}
});
};
il codice funziona come previsto, ma ho deciso di aggiungere alcune costanti per aiutare abbellire il codice e migliorare leggibilità. Ho per esempio diversi posti nel mio codice dove sto verificando xhr.status == 200 o xhr.status == 400 e così via.
mi può dichiarare variabili di classe come Rest.prototype.STATUS_OK = 200;
Ma variabile è modificabile, e non posso pensare a come farli costante. Per esempio nel mio codice posso fare un this.STATUS_OK = 123;
e questo modificherà la variabile. Ho giocato con la parola chiave const, senza fortuna.
ho visto questo: Where to declare class constants?, ma non è stato di grande aiuto.
Qualcuno può indicarmi la giusta direzione su come rendere questi campi un valore letterale costante anziché una variabile?
Si noti che i "campi" sono * proprietà *, non * variabili *. Per le variabili potresti semplicemente usare la [parola chiave 'const'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) dove supportata. Ma lo faresti localmente comunque :-) – Bergi