javascript use strictを使用する
- 2020.09.21
- javascript
- javascript

javascriptで、use strictを使用すると厳格モードでコードを記述することができ、エラーチェックを行うことができます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 84.0.4147.105
use strict使い方
まずは、use strictを使用せずに記述したコードを実行してみます。
1 2 3 4 5 6 |
<script> str = "文字"; // 変数宣言なし console.log(str); // 文字と表示される </script> |
次に同様のコードに「use strict」を使用して実行してます。
1 2 3 4 5 6 7 8 |
<script> "use strict"; str = "文字"; console.log(str); </script> |
変数宣言がされていないためエラーとなります。

以下のように変数宣言を行うとエラーはなくなります。
1 2 3 4 5 6 7 8 |
<script> "use strict"; var str = "文字"; console.log(str); // 文字と表示される </script> |
エラーになる構文
関数の引数名重複
関数の引数名が重複した場合は
「Uncaught SyntaxError: Duplicate parameter name not allowed in this context」となります。
1 2 3 4 |
'use strict'; function hoge(a, a){ } |

使用しない場合はエラーにならず、以下の結果となります。
1 2 3 4 5 |
function hoge(a, a){ console.log(a + a) } hoge(1,2) // 4 |
with構文の利用
with構文を利用した場合は、
「Uncaught SyntaxError: Strict mode code may not include a with statement」が発生します。
1 2 3 4 5 6 |
'use strict'; with(Math){ console.log(max(1,2,3)); console.log(min(1,2,3)); } |

使用しない場合はエラーにならず、以下の結果となります。
1 2 3 4 |
with(Math){ console.log(max(1,2,3)); // 3 console.log(min(1,2,3)); // 1 } |
0xでの8進数の表記
0xで8進数を表示した場合は
「Uncaught SyntaxError: Octal literals are not allowed in strict mode.」となります。
1 2 3 4 5 |
'use strict'; const num = 011; console.log(num); |

使用しない場合はエラーにならず、以下の結果となります。
1 2 3 |
const num = 011; console.log(num); // 9 |
外で定義したthisの関数内での利用
外で定義したthisを関数内で利用した場合は、
「Uncaught TypeError: Cannot read property ‘num’ of undefined」となります。
1 2 3 4 5 6 7 |
'use strict'; this.num = 1; function hoge(){ console.log(this.num) } hoge(); |

使用しない場合はエラーにならず、以下の結果となります。
1 2 3 4 5 |
this.num = 1; function hoge(){ console.log(this.num) } hoge(); // 1 |
将来のキーワードとして予約されいるワードを使用
将来のキーワードとして予約されている「implements,interface,let,package,private,protected,public,static,yield」を変数名として使用した場合は
「Uncaught SyntaxError: Unexpected strict mode reserved word」となります。
1 2 3 4 5 |
'use strict'; let yield = 'hoge'; console.log(yield); |

使用しない場合はエラーにならず、以下の結果となります。
1 2 3 |
let yield = 'hoge'; console.log(yield); // hoge |
適用範囲
関数の中で、使用すると適応範囲は関数の中のみとなります。
1 2 3 4 5 6 |
function hoge(){ 'use strict'; } str = "文字"; // 変数宣言だけどエラーにはならない |
-
前の記事
javascript 文字列を日付に変更する 2020.09.21
-
次の記事
React.js ライブラリ「react-customizable-progressbar」を使って円形のSVGプログレスバーを実装する 2020.09.22
コメントを書く