Javascript原型常量声明

Hus*_*man 7 javascript oop

我正在使用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");
                }
            }
        });
    };
Run Code Online (Sandbox Code Playgroud)

代码按预期工作,但我决定添加一些常量来帮助美化代码并提高可读性.我在我的代码中有几个地方,我正在检查xhr.status == 200或xhr.status == 400等等.

我可以将类变量声明为 Rest.prototype.STATUS_OK = 200;

但变量是可编辑的,我想不出如何使它们保持不变.例如,在我的代码中,我可以做一个this.STATUS_OK = 123;,这将修改变量.我玩过const关键字,没有运气.

我已经看到了:在哪里声明类常量?,但没有多大帮助.

有人能指出我正确的方向,如何使这些字段成为常量文字而不是变量?

aps*_*ers 10

使用ECMAScript 5,Object.defineProperty您可以使值不可设置:

Object.defineProperty(Rest, "STATUS_OK", {
  enumerable: false,   // optional; if you care about your enumerated keys
  configurable: false,
  writable: false,
  value: 200
});
Run Code Online (Sandbox Code Playgroud)

或者,由于这些是默认值,只需执行以下操作:

Object.defineProperty(Rest, "STATUS_OK", { value: 200 });
Run Code Online (Sandbox Code Playgroud)

这会在访问时产生Rest.STATUS_OK收益200,但它不会响应重新定义它或delete它的尝试.此外,configurable: false将阻止任何尝试通过后续defineProperty调用重新定义属性.

但是,这不适用于不支持ES5的旧版浏览器defineProperty(特别是IE8及以下版本).

  • @Husman:实际上你可以省略除了`value`之外的所有行,因为`false`是那些行的默认值. (5认同)