M
Mehmet Yavuz S. Soyturk
Hello,
consider the next code:
var obj = {};
with(obj) {
var x = 10;
}
print(x);
print(obj.x);
It prints 10 and undefined. Here, one could expect that obj.x get the
value 10. But it's not the case, because variable declarations are
placed at the start of function code (or global code), so the
previous code is equivalent with:
var obj;
var x;
obj = {};
with(obj) {
x = 10;
}
print(x);
print(obj.x);
You can clearly see now that x is placed in the outer context. But
consider the next:
var obj = {};
with(obj) {
eval("var x = 10;");
}
print(x);
print(obj.x);
I was expecting that obj.x would get the value 10 here. But no, it
gives the same output as the previous code. I tested it with
spidermonkey, kjs and ie jscript. Looking at the ECMA spec, I could
not find anything that describes that behaviour.
has obj as the variable object. var x = 10 is parsed as a program, and
executed in that context.
A program "var x = 10" creates a variable x in the current variable
object (in that case obj), and assigns it the value 10.
But why does it not like that in spidermonkey, kjs and ie? Did I
misinterpret the spec, or are they not standard compliant?
I know that one does not want to write code like this. I ask this,
because I'm writing a compiler for ECMAScript.
consider the next code:
var obj = {};
with(obj) {
var x = 10;
}
print(x);
print(obj.x);
It prints 10 and undefined. Here, one could expect that obj.x get the
value 10. But it's not the case, because variable declarations are
placed at the start of function code (or global code), so the
previous code is equivalent with:
var obj;
var x;
obj = {};
with(obj) {
x = 10;
}
print(x);
print(obj.x);
You can clearly see now that x is placed in the outer context. But
consider the next:
var obj = {};
with(obj) {
eval("var x = 10;");
}
print(x);
print(obj.x);
I was expecting that obj.x would get the value 10 here. But no, it
gives the same output as the previous code. I tested it with
spidermonkey, kjs and ie jscript. Looking at the ECMA spec, I could
not find anything that describes that behaviour.
executes in the same context as the body of the with statement, whichFrom ECMA 262, sections 10.2.2 and 15.1.2.1, I can say that eval
has obj as the variable object. var x = 10 is parsed as a program, and
executed in that context.
A program "var x = 10" creates a variable x in the current variable
object (in that case obj), and assigns it the value 10.
But why does it not like that in spidermonkey, kjs and ie? Did I
misinterpret the spec, or are they not standard compliant?
I know that one does not want to write code like this. I ask this,
because I'm writing a compiler for ECMAScript.