本章列出了一些与 ES6 代码风格相关的建议。
var
与 let
与 const
(详情请参阅变量章节)
const
。您可以将其用于所有值永不改变的变量。let
– 用于值会发生变化的变量。var
。
readFilePromisified
(
filename
)
.
then
(
text
=>
console
.
log
(
text
))
对于多行函数,传统函数也可以很好地工作(需要注意的是 this
不是词法作用域)。
readFilePromisified
(
filename
)
.
then
(
function
(
text
)
{
const
obj
=
JSON
.
parse
(
text
);
console
.
log
(
JSON
.
stringify
(
obj
,
null
,
4
));
});
单行函数往往是一次性的。如果不是,那么传统函数的优势在于您可以为其命名,这对于文档和调试非常有用。
},
结尾。
const
obj
=
{
foo
()
{
},
bar
()
{
},
};
// Generator function declaration
function
*
genFunc
()
{
···
}
// Generator function expression
const
genFunc
=
function
*
()
{
···
};
// Generator method definition in an object literal
const
obj
=
{
*
generatorMethod
()
{
···
}
};
// Generator method definition in a class definition
class
MyClass
{
*
generatorMethod
()
{
···
}
}
详情请参阅生成器章节。
// Mark optional parameters via the parameter default value `undefined`
function
foo
(
optional
=
undefined
)
{
···
}
// Mark required parameters via a function that throws an exception
function
foo
(
required
=
throwException
())
{
···
}
// Enforcing a maximum arity (variant 1 of 2)
function
f
(
x
,
y
,
...
empty
)
{
// max arity: 2
if
(
empty
.
length
>
0
)
{
throw
new
Error
();
}
}
// Enforcing a maximum arity (variant 2 of 2)
function
f
(
x
,
y
)
{
// max arity: 2
if
(
arguments
.
length
>
2
)
{
throw
new
Error
();
}
}
此外,“Speaking JavaScript”中的ES5 代码风格建议仍然适用于 ES6。