瀏覽器:在Strict mode跟沒有Strict mode下的瀏覽器會有不同的執行結果。
如何進入Strict mode:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
'use strict'
function foo1() {
console.log(this);
}
foo1(); //指向window物件
function foo() {
'use strict'; //進入Strict mode
console.log(this);
}
foo(); //undefined
<script>
'use strict'
myName = 'Emma'; //Uncaught ReferenceError
<script>
'use strict'
var myName = 'Emma';
delete myName; //Uncaught SyntaxError
<script>
'use strict'
function sum(a, b) {
return a + b;
}
delete sum; //Uncaught SyntaxError
<script>
'use strict'
function square(a, a) { // Uncaught SyntaxError
return a * a;
}
console.log(square(2, 2));
<script>
'use strict'
var obj1 = {};
Object.defineProperty(obj1, "x", { value: 42, writable: false });
obj1.x = 9 //Uncaught TypeError
<script>
'use strict';
var obj2 = { get x() { return 17; } };
obj2.x = 5; //Uncaught TypeError
<script>
'use strict';
var fixed = {};
Object.preventExtensions(fixed);
fixed.newProp = "ohai" //Uncaught TypeError
<script>
'use strict';
var x = 010; // Uncaught SyntaxError
console.log(parseInt(x));
<script>
var name = 'Tom';
var name2 = eval("var name = 'Mary';");
console.log(name); //Mary
<script>
'use strict'
var name = 'Tom';
var name2 = eval("var name = 'Mary';");
console.log(name); //Tom
<script>
'use strict';
var eval = 10;
console.log(eval); //Uncaught SyntaxError
參考文章: