मैं एक विश्वसनीय API के साथ काम कर रहा हूं, और मेरा जावास्क्रिप्ट कोड jQuery के $ .ajax() कॉल के माध्यम से आरईएसटी क्वेरी कर रहा है।जावास्क्रिप्ट प्रोटोटाइप निरंतर घोषणा
मैं (बहुत सरल) एक जावास्क्रिप्ट बाकी वर्ग है, जो मैं नीचे प्रदर्शित करेगी लागू कर दिया है:
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;
कर सकता हूं और यह चर को संशोधित करेगा। मैंने बिना भाग्य के, कॉन्स कीवर्ड के साथ खेला है।
मैंने यह देखा है: Where to declare class constants?, लेकिन यह बहुत मदद नहीं थी।
क्या कोई मुझे सही दिशा में इंगित कर सकता है कि इन क्षेत्रों को चर के बजाय निरंतर शाब्दिक कैसे बनाया जाए?
कृपया ध्यान दें कि "फ़ील्ड" * गुण * हैं, नहीं * चर *। चर के लिए आप बस ['const' कीवर्ड] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) का उपयोग कर सकते हैं जहां समर्थित है। लेकिन आप वैसे भी स्थानीय-स्कोप करेंगे :-) – Bergi