欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

原生JS中應(yīng)該禁止出現(xiàn)的寫法

 更新時間:2021年05月04日 11:46:15   作者:淺笑·  
這篇文章主要介紹了原生JS中應(yīng)該禁止出現(xiàn)的寫法,以提高代碼效率和安全性,對效率和安全感興趣的同學,可以參考下

塊級函數(shù)

嚴格模式下,在 ES6 之前應(yīng)禁止使用。ES6 開始可以使用,函數(shù)的作用域為聲明該函數(shù)的塊內(nèi)部。非嚴格模式下應(yīng)禁止使用。

if(true) {
    function test() { //塊級函數(shù)
        console.log(1);
    }
}
test();

直接修改對象的 prototype 原型

瀏覽器對原型進行了優(yōu)化,在調(diào)用實例之前,會為對象的方法提前規(guī)劃內(nèi)存位置。所以不可以直接修改 prototype 原型。以下兩種方法都應(yīng)禁止使用

使用 Object.setPrototypeOf 修改原型

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

直接修改對象的 __proto__ 屬性

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

with 的用法:

var a = {
    p1: 1,
    p2: 2
}
with (a) {
    p1 = 3;
}
console.log(a.p1);

應(yīng)該禁止使用 with,例如:

function a(arg1, arg2) {
  with (arg2){
    console.log(arg1); // 無法確定是要輸出第一個參數(shù)還是要輸出 arg2 的 arg1 屬性
  }
}
var arg2 = {arg1:1}
a("arg1", arg2)

callee

arguments.callee 表示當前正在執(zhí)行的函數(shù):

function a(arg1) {
    if (arg1 > 1) {
        return arg1 * arguments.callee(arg1 - 1);
    }
    else {
        return 1;
    }
}
console.log(a(3)); // 6

當一個函數(shù)必須調(diào)用自身的時候, 應(yīng)禁止使用arguments.callee(),直接通過函數(shù)名字調(diào)用該函數(shù)。

function a(arg1) {
    if (arg1 > 1) {
        return arg1 * a(arg1 - 1); // 直接通過函數(shù)名稱調(diào)用
    }
    else {
        return 1;
    }
}
console.log(a(3)); // 6

caller

caller 表示函數(shù)的調(diào)用者,應(yīng)禁止使用,該特性不是標準的。

function a() {
    console.log(a.caller); // function b() { a(); }
}
function b() {
    a();
}
b();

eval

eval() 可以把傳入的字符串參數(shù)當成JavaScript代碼執(zhí)行。

eval("var a = 1, b = 2; console.log(a+b)"); // 3

禁止使用 eval。eval 比一般JavaScript執(zhí)行要慢,因為瀏覽器對 javascript 進行了優(yōu)化。eval 方法也不安全,因為它使用與調(diào)用者相同的權(quán)限執(zhí)行代碼,而且 eval() 被調(diào)用時,它的作用域也會暴露。應(yīng)該用 Function 代替:

var a = new Function("a", "b", "console.log(a+b)")
a(1,2); // 3

以上就是原生JS中應(yīng)該禁止出現(xiàn)的寫法的詳細內(nèi)容,更多關(guān)于原生JS中應(yīng)該禁止的寫法的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論