简体   繁体   English

node.js是否支持'let'语句?

[英]Does node.js support the 'let' statement?

Does node.js support a let statement something like what's described on MDN? node.js是否支持let语句,类似于MDN描述的内容? ?

var x = 8,
    y = 12;

let ( x = 5, y = 10) {
    return x + y;
} //15

If not, is there a way to duplicate the functionality with a self-executing anonymous function or something? 如果没有,是否有办法使用自执行匿名功能或其他功能来复制功能?

And/or is there another js environment that 和/或还有另一个js环境

  1. has let and and let
  2. has a REPL, as node does? 像节点一样具有REPL? Rhino? 犀牛?

EDIT : 编辑

This question was asked quite a while ago. 这个问题是很久以前问过的。 As of now, late 2015, the answer is "Yes, yes it does". 截至2015年末,答案是“是的,是的”。 Harmony features were included by default in io.js 3.3, and have been recently brought back to node.js with the 4.x release. io.js 3.3中默认包括了Harmony功能,最近在4.x版本中又将其引入了node.js。

Yes, you can use let within node.js, however you have to run node using the optional --harmony flag. 是的,可以在node.js中使用let,但是必须使用可选的--harmony标志运行node。 Try the following test.js : 试试下面的test.js

"use strict"
var x = 8,
    y = 12;

{ let x = 5, y = 10; console.log(x + y); }

console.log(x + y);

And then run the file node --harmony test.js which results in: 然后运行文件node --harmony test.js ,结果为:

15
20

I would not recommend using this in an important production application, but the functionality is available now. 我不建议在重要的生产应用程序中使用此功能,但是该功能现在可用。

This is an old question and the accepted answer is no longer correct. 这是一个古老的问题,被接受的答案不再正确。

let support was added in Node.js 4.x . let在Node.js 4.x中添加了支持。

See here for the full version support matrix. 有关完整版本支持列表,请参见此处

node --use_strict --harmony_scoping

I don't think Node supports let , but you can do this: 我认为Node不支持let ,但是您可以这样做:

var a = 5;

(function () {
  var a = 6;
  console.log(a); // => 6
})();

console.log(a); // => 5

You can use the Babel transpiler and use let as well as many other ES6/ES2015 features. 您可以使用Babel转译器并使用let以及许多其他ES6 / ES2015功能。

To use babel: 要使用babel:

$ npm install --save-dev babel

Then in your package.json : 然后在您的package.json

"scripts": {
  "start": "babel-node index.js"
}

Inside index.js : 内部index.js

let foo  = 'bar;

Then start the server: 然后启动服务器:

$ npm start

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

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