我正在使用RESTful API,并且我的Javascript代码通过jQuery的$.ajax()调用进行REST查询。
我已经实现了一个Javascript Rest类,下面是展示的简化版:
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
关键字即可。 但是无论如何,您都会将其限制为本地范围 :-) - Bergi