Read a lot of JavaScript strict mode, which has said "Disable with statement", previously seen this is riding on the flowers, around the area, because usually rarely used this statement, the ban can not help to their relationship is not very big. Today, I can't help wondering why the "strict mode" doesn't allow the WITH statement?
The ECMAScript specification says that "with statement is used to set the scope of code in a particular object", you can see that the WITH statement changes the scope chain.
function Person (name,age,sex) {
this.name = name;
This.age = age;
This.sex = sex;
}
(function () {
var title = ' Applicant: ';
var Zhangsan = new Person (' John ', 20, ' Male ');
var str = ';
With (Zhangsan) {
str = title+name+ ', age ' +age+ ' age, ' +sex+ ' sex ' + ', position ' +job;
}
Console.log (str);
}) ();
The code above will report uncaught Referenceerror:job is not defined.
If the WITH statement block above is changed to
str = title+zhangsan.name+ ', age ' +zhangsan.age+ ', ' +zhangsan.sex+ ' sex ' + ', position ' +zhangsan.job;
No error, Output str: Applicant: John, age 20, male, post undefined
For a variable in a with statement block, when executed, check whether its properties are in Zhangsan.
We know that when you run a script, you need two processes, first compiled, and then executed.
Obviously, at compile time, it is not possible to determine the attributes of the object represented by this variable Zhangsan. You can only determine if Zhangsan is an instance of person at execution time. Therefore, it is not possible at compile time whether the variables in the WITH statement block are Zhangsan properties or variables in the scope chain of the previous layer variable.
This is not difficult to understand because strict mode disables the WITH statement when the strict mode has compile-time checks to see if the variable defines a conflict, so strict mode does not allow it to exist.