我正在使用RESTful API,並且我的Javascript代碼通過jQuery的$ .ajax()調用進行REST查詢。Javascript原型常量聲明
我實現了一個JavaScript的休息課,我將在下面顯示(大大簡化):
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");
}
}
});
};
代碼工作的預期,但我已經決定增加一些常量,幫助美化代碼和提高可讀性。例如,我在我的代碼中檢查了xhr.status == 200或xhr.status == 400等幾個地方。
我可以聲明類變量爲Rest.prototype.STATUS_OK = 200;
但變量是編輯,我想不出如何使他們不斷。在我的代碼例如,我可以做一個this.STATUS_OK = 123;
,這將修改變量。我玩過const關鍵字,沒有運氣。
我看到這個:Where to declare class constants?,但它沒有太大的幫助。
有人能指出我在正確的方向,如何使這些領域的常量文字而不是變量?
請注意,「字段」是*屬性*,而不是*變量*。對於變量,您可以在支持的地方使用['const' keyword](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const)。但是無論如何,你會在本地範圍內:-) – Bergi