在 ecmascript 6 中定义 setter 时出错

Error when defining a setter in ecmascript 6

我正在尝试在 ecmascript 6 中定义 class。

这是代码:

class Machine {
   constructor (){
      this._context = null;
   }

   get context (){
      return this._context;
   }

   set context (context){
      this._context = context;
   }   
}

但是对于 Webstorm 中的 setter 我总是得到同样的错误: "Set accessor method has type that is not compatible with get accessor type"

我不明白为什么会出现此错误。我完全按照这里的解释做了:http://es6-features.org/#GetterSetter

EDIT :似乎问题只存在于我在 angular 工厂中定义 class。

所以我的问题是如何在 angular 工厂中正确定义 class?

也许我不应该那样做。

编辑 2:这是我的 angular 工厂:

angular.module('frontEndApp')
  .factory('Machine', function () {

     class Machine {
        constructor (){
           this._context = null;
        }

        get context (){
           return this._context;
        }

        set context (context){
           this._context = context;
        }   
     }

     return Machine;
  }

你的 ES6 (ES2015) 代码是正确的。听起来像是 WebStorm 中围绕新语法的错误(尽管 "type" 这个词令人惊讶,因为 JavaScript 是松散类型的;您可能需要检查您是否没有将它设置为 TypeScript 或类似的) .

这是您的 Webstorm 设置问题。你有 linter 或其他东西吗 运行?它是自动检测语言并且出于某种原因不选择 JS 吗?

代码没问题。

我想 WebStorm 无法确定 属性 this._context 的类型 您可能想要注释您的代码以帮助 WebStorm(我遇到了同样的问题):

class Machine {
   constructor (){
      this._context = null;
   }

  /**
   * Proxy method for getting context.
   *
   * @return {ContextInterface}
   */
   get context (){
      return this._context;
   }

   /**
    * Sets the appropriate context.
    *
    * @param {ContextInterface} context
    */
   set context (context){
      this._context = context;
   }   
}