简体   繁体   English

在类中使用const和arrow函数时出现SyntaxError

[英]SyntaxError when using const and arrow function inside a class

I'm working through some CodeWars katas and I would like to know: For what reason does this syntax work... 我正在研究一些CodeWars katas,我想知道:这种语法为何起作用?

class SmallestIntegerFinder {
  findSmallestInt(args) {
    return Math.min(...args)
  }
}

...but this other does not? ...但是这不是吗?

class SmallestIntegerFinder {
  const findSmallestInt = args => Math.min(...args)
}

This is the error trace printed: 这是打印的错误跟踪:

const findSmallestInt = args => Math.min(...args)
      ^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
    at createScript (vm.js:56:10)
    at Object.runInThisContext (vm.js:97:10)
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at 
    at evalScript (bootstrap_node.js:353:27)
    at run (bootstrap_node.js:122:11)
    at run (bootstrap_node.js:389:7)
    at startup (bootstrap_node.js:121:9)
    at bootstrap_node.js:504:3

I haven't had any problem using the second syntax in other katas, but this is the first time I use it inside a class, so I guess it has something to do with JavaScript classes that I haven't learnt yet or something else that is escaping me at the moment. 在其他kata中使用第二种语法我没有任何问题,但这是我第一次在类中使用它,因此我想它与我尚未学习的JavaScript类有关,或者与其他方面有关目前正在逃避我。

Thanks in advance! 提前致谢!

It's because that's not valid syntax. 这是因为这不是有效的语法。 Within a class, you do not use variable bindings like const , let , or var to define members. 在类中,您不使用像constletvar这样的变量绑定来定义成员。 The syntax is nice and simple. 语法很好,很简单。

There is a proposal, however, that will allow class fields , similar to your second example. 但是,有一个建议将允许类字段 ,类似于您的第二个示例。 However, you would still not use const , let , or var to define these either. 但是,您仍然不会使用constletvar来定义它们。

Edited: thanks @Bergi for pointing out that class/instance method syntax isn't sugar for anything, that's just how you define methods. 编辑:感谢@Bergi指出类/实例方法语法对任何事情都不是糖,这只是您定义方法的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM