本章列出一些與 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。