I work with a RESTful API, and my Javascript code makes REST requests using jQuery $ .ajax () call.
I implemented the javascript JavaScript class, which I will show below (greatly simplified):
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"); } } }); };
The code works as intended, but I decided to add some constants to help decorate the code and improve readability. I have several places in my code where I check xhr.status == 200 or xhr.status == 400, etc.
I can declare class variables as Rest.prototype.STATUS_OK = 200;
But the variable is editable, and I canβt figure out how to make it constant. In my code, for example, I can do this.STATUS_OK = 123; and this will change this variable. I played with the const keyword, with no luck.
I saw this: Where to declare class constants? , but it did not help.
Can someone point me in the right direction how to make these fields a constant literal instead of a variable?