es5までは関数にデフォルト因数を指定する場合、以下のように書いてました。
1
2
3
4
5
6
7
8
9
10
11
|
function makeAjaxRequest(url, method) {
if (!method) {
method = 'GET'
}
return method;
}
makeAjaxRequest('google.com');
=> GET
makeAjaxRequest('google.com', 'POST');
=> POST
|
これがes6では、引数のところに与えたいデフォルト値を設定します。
1
2
3
4
5
6
7
8
|
function makeAjaxRequest(url, method = 'GET') {
return method;
}
makeAjaxRequest('google.com');
=> GET
makeAjaxRequest('google.com', 'POST');
=> POST
|
null
にしたい場合は、
1
2
3
4
5
6
7
8
|
function makeAjaxRequest(url, method = 'GET') {
return method;
}
makeAjaxRequest('google.com', null);
=> null
makeAjaxRequest('google.com', 'POST');
=> POST
|
注意点としてundefined
にすると指定しなかったと解され、デフォルト値のGET
が返る。
See Also