I have read the strict JavaScript mode many times, and some say "disable With statements". In the past, I saw this all by riding a horse and watching flowers, and passed by, because I rarely use this statement in normal times, so it doesn't have much to do with myself. Today I can’t help but wonder why the “strict model” can’t tolerate the with statement?
The EcmaScript specification says that "the with statement is used to set the scope of the code in a specific object". It can be seen 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('Zhang San',20,'male');var str = '';with(zhangsan){str = title+name+', age'+age+'years,'+sex+'sex'+', position'+job;}console.log(str);})();The above code will report Uncaught ReferenceError: job is not defined.
If the above with statement block is changed to
str = title+zhangsan.name+', age'+zhangsan.age+'years,'+zhangsan.sex+'sex'+', position'+zhangsan.job;
There is no error, the output is: Applicant: Zhang San, 20 years old, male, undefined position
For variables in the with statement block, when executing, you must check whether their properties are in zhangsan.
We know that when running a script, there are two processes that are needed, first compile and then execute.
Obviously, when compiling, it is not possible to determine what properties the object represented by this variable of zhangsan have. It can only be determined that zhangsan is an instance of Person when executed. Therefore, it cannot be true that the variable in the with statement block is a property of zhangsan or a variable in the previous variable scope chain during compilation.
This conflicts with the fact that the variable is defined when compiling the strict mode, so the strict mode does not allow the difference to exist. Therefore, it is not difficult to understand that the With statement is disabled in strict mode.