【问题标题】:how to define class level constant in ES6 class [duplicate]如何在 ES6 类中定义类级常量 [重复]
【发布时间】:2017-10-01 16:30:30
【问题描述】:

我们如何定义类级常量并在静态和实例方法中访问它?

 class ExternalRequests{

      const HEADERS = { "Accept":  "application/json, text/plain", "Content-Type": "application/json", "Access-Control-Allow-Origin": "*"}


      static get(url){
        return fetch(url, {method: 'get', HEADERS})
        .catch(_ => {
          throw new Error("network error");
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          return response.json();
        });
      }

      static post(url, data){
        return fetch(url, {method: 'post', HEADERS, body: data})
        .catch(_ => {
          throw new Error("network error");
        })
        .then(response => {
          if (!response.ok) {
             throw new Error(response.statusText);
          }
          return response.json();
        });
      }

     static put(url, data){
        return fetch(url, {method: 'put', HEADERS, body: data})
        .catch(_ => {
          throw new Error("network error");
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          return response.json();
        });
      }

      static delete(){
       return fetch(url, {method: 'delete', HEADERS})
        .catch(_ => {
          throw new Error("network error");
        })
        .then(response => {
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          return response.json();
        });
      }

    }

    export default ExternalRequests;

错误

ERROR in ./externalRequests.js
Module build failed: SyntaxError: Unexpected token (3:8)

  1 | class ExternalRequests{
  2 | 
> 3 |   const HEADERS = { "Accept":  "application/json, text/plain", "Content-Type": "application/json", "Access-Control-Allow-Origin": "*"}

【问题讨论】:

  • 如果你的类上的每个方法都是static,那么你不需要或不需要一个类,你只需要一个对象。如果你只是导出一个默认对象,你真正想要的是一堆命名的导出。

标签: javascript ecmascript-6 es6-promise es6-class


【解决方案1】:

将其更改为static get 访问器。然后,您可以从其他静态方法以this.HEADERS 的身份访问它。 (不幸的是,这是在 JS 获得类属性之前我们得到的最好的)

class ExternalRequests{
  static get HEADERS() {
    return { 
      "Accept":  "application/json, text/plain", 
      "Content-Type": "application/json", 
      "Access-Control-Allow-Origin": "*"
    }
  }

  static get(url){
    return fetch(url, {method: 'get', this.HEADERS})
  }
/* rest of the class ... */

如果你现在想使用类属性,你可以使用babel-transform-class-properties,这样你可以这样做:

class ExternalRequests {
  static HEADERS = /* ... your headers */
  /* ...rest of the class... */

【讨论】:

    猜你喜欢
    • 2016-05-16
    • 2018-06-09
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2017-10-05
    • 2018-12-06
    • 2016-10-06
    • 2020-09-18
    相关资源
    最近更新 更多