2017-08-17 182 views
0

也许类似于How do I configure ESLint to allow fat arrow class methodsESLint示出了类实例属性错误初始化为箭头功能

当类方法定义为箭头函数Eslint高亮错误“方法”没有定义。 (无为undef)。 简单的例子

class abc { 
    d =() => { 
    // method body 
    } 
} 

这里就不difined 'd'

class method is not defined

我.eslintrc配置

{ 
    "env": { 
     "browser": true, 
     "es6": true 
    }, 
    "extends": [ 
     "eslint:recommended", 
     "plugin:flowtype/recommended" 
    ], 
    "parser": "babel-eslint", 
    "parserOptions": { 
     "ecmaFeatures": { 
      "experimentalObjectRestSpread": true, 
      "jsx": true 
     }, 
     "sourceType": "module" 
    }, 
    "plugins": [ 
     "react", 
     "flowtype" 
    ], 
    "rules": { 
     "indent": [ 
      "error", 
      2 
     ], 
     "linebreak-style": [ 
      "error", 
      "unix" 
     ], 
     "quotes": [ 
      "error", 
      "single" 
     ], 
     "semi": [ 
      "error", 
      "always" 
     ] 
    } 
} 

.babelrc

{ 
    "presets": ["react", "es2015", "stage-1", "flow"] 
} 

也许我需要声明一些规则?

+1

ES6类没有实例变量,这就是'd'在这里。 – 2017-08-17 03:47:07

+0

箭头函数在'class'中没有意义 - 就像设置'Something.prototype.somefunction =()=> {}'没有意义 –

+0

@torazaburo - 'class'语法不提供实例变量,但是如果在方法中创建的话,结果类可以拥有它们。 (正在选择措辞。)(所以我的措辞可能也是错误的。) – nnnnnn

回答

1

正如MinusFour answer所提到的,我尝试通过命令行运行eslint,但没有看到该错误。

我的编辑器配置错误。 (原子的linter-eslint包中的node_modules文件夹路径错误)。在我删除这个路径并重新启动编辑器后,一切正常。

2

当在class定义,一个函数使用不同的语法:

class abc { 
    d() { 
    // method body 
    } 
} 

Javascript Classes

+1

当我们使用Babel transpiler时,我们可以将箭头函数设置为方法并获得一些利润(例如,在创建基于React.Component的类时,不需要绑定这个)。 您可以在这里看到示例:[处理事件示例](https://facebook.github.io/react/docs/handling-events.html) – n06rin

+0

很高兴知道,感谢您的信息!我不知道这个实验性功能,肯定会有用 –

0

This is something that hasn't made its way into Javascript yet。它可以作为带有babel的实验性插件使用,因此您需要更改默认的eslint解析器,并使用babel-eslint

+0

是的,你是对的。在.eslint配置文件中,我将解析器设置为babel-eslint(您可以在问题中看到它)。但它没有帮助。 – n06rin

+0

@ n06rin,我刚刚注意到了。它对我来说工作得很好,你正在使用哪个版本的eslint和babel-eslint? – MinusFour

+0

我使用[email protected]和[email protected] – n06rin