嚴格模式下,在 ES6 以前應禁止使用。ES6 開始能夠使用,函數的做用域爲聲明該函數的塊內部。非嚴格模式下應禁止使用。javascript
if(true) { function test() { //塊級函數 console.log(1); } } test();
瀏覽器對原型進行了優化,在調用實例以前,會爲對象的方法提早規劃內存位置。因此不能夠直接修改 prototype 原型。如下兩種方法都應禁止使用java
function a(){} a.prototype = { a_prop: "a val" }; function b(){} var proto = { b_prop: "b val" }; Object.setPrototypeOf( proto, a.prototype ); b.prototype = proto; var test = new b; console.log(test.a_prop); // a val console.log(test.b_prop); // b val
function a(){} a.prototype = { a_prop: "a val" }; function b(){} var proto = { b_prop: "b val", __proto__: a.prototype //直接修改 b 對象的 __prototype__ 屬性 }; b.prototype = proto; var test = new b; console.log(test.a_prop); // a val console.log(test.b_prop); // b val
with 的用法:瀏覽器
var a = { p1: 1, p2: 2 } with (a) { p1 = 3; } console.log(a.p1);
應該禁止使用 with,例如:安全
function a(arg1, arg2) { with (arg2){ console.log(arg1); // 沒法肯定是要輸出第一個參數仍是要輸出 arg2 的 arg1 屬性 } } var arg2 = {arg1:1} a("arg1", arg2)
arguments.callee 表示當前正在執行的函數:函數
function a(arg1) { if (arg1 > 1) { return arg1 * arguments.callee(arg1 - 1); } else { return 1; } } console.log(a(3)); // 6
當一個函數必須調用自身的時候, 應禁止使用 arguments.callee(),直接經過函數名字調用該函數。優化
function a(arg1) { if (arg1 > 1) { return arg1 * a(arg1 - 1); // 直接經過函數名稱調用 } else { return 1; } } console.log(a(3)); // 6
caller 表示函數的調用者,應禁止使用,該特性不是標準的。prototype
function a() { console.log(a.caller); // function b() { a(); } } function b() { a(); } b();
eval() 能夠把傳入的字符串參數當成 javascript 代碼執行。code
eval("var a = 1, b = 2; console.log(a+b)"); // 3
禁止使用 eval。eval 比通常 javascript 執行要慢,由於瀏覽器對 javascript 進行了優化。eval 方法也不安全,由於它使用與調用者相同的權限執行代碼,並且 eval() 被調用時,它的做用域也會暴露。應該用 Function 代替:對象
var a = new Function("a", "b", "console.log(a+b)") a(1,2); // 3