Хабр Курсы для всех
РЕКЛАМА
Практикум, Хекслет, SkyPro, авторские курсы — собрали всех и попросили скидки. Осталось выбрать!
существенный недостатокwith({}) { var x = "abc"; } console.log(x) // 'abc'
with({}) { var this.x = "abc"; }
console.log(x); // undefinedvar this.x = "abc";with({}) { this.x = "abc"; }
console.log(x);х = 123
123
with ({}) { this.x = "abc" }
"abc"
x
"abc"with ({}) { console.log(this) }
DOMWindow
undefinedthis.a=1;
with ({x:'1'}) {
console.log(this); // { a: 1 }
}
var x='a';
with({x:'b'}) {
console.log('1:'+x); // 1:b
x = 'c';
console.log('2:'+x); // 2:c
}
console.log('3:'+x); // 3:aa = 0;
with ({b: 1, c: 2}) {
a = b + c;
}
a == 3;
a = 0;
for (var i = 4; i--;) {
a += i;
}
var o = {};
with (o) {
y = 1;
console.log(y); // 1
}
console.log(y); // 1
with (o) {
y = 1;
console.log(y); // 1
o.y = 2;
console.log(y); // 2
y = 3;
console.log(y); // 3
}
console.log(y); // 1
with({ x: 'abc' }) { }
console.log(x) // undefined
function exec(__code__, scope) { with(scope || global) return eval(__code__); } Да, я еретик и отступник, горетть мне в аду! with(obj); // Error
with({ x: 123 }); // Success
<span>0</span>
<span>1</span>
<span>2</span>
<span>3</span>
for (var i = 4; i--;) {
$$('span')[i].onclick = function () {
alert(i); // fail
};
}
// IIFE
for (var i = 4; i--;) {
$$('span')[i].onclick = function (i) {
return function () {
alert(i); // success
};
}(i);
}
// with
for (var i = 4; i--;) with({ i:i }) {
$$('span')[i].onclick = function () {
alert(i); // success
};
}
Оператор with и почему его не стоит использовать