分別運行下面兩段代碼
- 使用with的時候:test__time: 390.218ms
const obj = { cunt: 122 };
function test_with() {
with (obj) {
for (let i = 0; i < 1e6; i++) {
cunt = 100;
a = 0;
}
}
console.log(a);
console.log(obj.cunt);
}
console.time("test___start");
test_with();
console.timeEnd("test___start");//test___start: 390.218ms
- 不用with的時候:test__time: 6.668ms
const obj = { cunt: 122 };
function test_with() {
for (let i = 0; i < 1e6; i++) {
obj.cunt = 100;
a = 0;
}
console.log(a);
console.log(obj.cunt);
}
console.time("test___start");
test_with();
console.timeEnd("test___start"); //test___start: 6.668ms
對比耗時 明顯with耗時更久,盡量不使用with
with(object){
statement;
}
- 總結一下:with會把object添加到作用域的頭部,然后執(zhí)行statement,與eval類似,with語句的javascript代碼非常難于優(yōu)化,同時也會給調(diào)試代碼造成困難,并且同沒有使用with語句的代碼相比,它運算得更慢.