Home > Article > Web Front-end > Reasons why JavaScript strict mode disables the With statement_javascript tips
I’ve read JavaScript strict mode many times, and one of them says “disable the With statement”. I’ve seen this before and just passed it by, because this statement is rarely used, so I can’t help but disable it for myself. None are very big. Today I can't help but wonder why "strict mode" cannot accommodate the with statement?
The EcmaScript specification says that "the with statement is used to set the scope of 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 = '申请人:'; var zhangsan = new Person('张三',20,'男'); var str = ''; with(zhangsan){ str = title+name+',年龄'+age+'岁,'+sex+'性'+',职位'+job; } console.log(str); })();
The above code will report Uncaught ReferenceError: job is not defined.
If you change the above with statement block to
str = title zhangsan.name ', age' zhangsan.age 'years,' zhangsan.sex 'sex' ', position' zhangsan.job;
No error is reported, and the output str is: Applicant: Zhang San, age 20, male, position undefined
For variables in the with statement block, when executing, check whether its attributes are in zhangsan.
We know that when running a script, two processes are required, first compilation and then execution.
Obviously at the time of compilation, it is not possible to determine what attributes the object represented by the variable zhangsan has. It can only be determined at execution time that zhangsan is an instance of Person. Therefore, it is impossible to confirm at compile time whether the variable in the with statement block is an attribute of zhangsan or a variable in the upper-level variable scope chain.
This conflicts with strict mode, which checks whether variables are defined at compile time, so strict mode will not allow differences to exist, so it is not difficult to understand that strict mode disables the With statement.