JavaScript strict mode for disabling the With statement

  • 2020-03-30 04:08:05
  • OfStack

Saw many times JavaScript strict mode, one of which said "disable With statement", before see this is riding a horse to view the flowers, along, because usually rarely used this statement, ban can not help to their relationship is not very big. Today I can't help wondering why "strict mode" doesn't have room for the with statement.

The EcmaScript specification says that "the with statement is used to set the scope of the code in a particular object," and as you can see, 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 old, '+sex+' sex '+' The position '+job;
}
console.log(str);
})();

The code above reports an Uncaught ReferenceError: job is not defined.

If you change the with block above to

STR = title+zhangsan.name+', age '+zhangsan.age+' years old, '+zhangsan.sex+', position '+zhangsan.job;

The output STR is: applicant: zhang SAN, age 20, male, position undefined

For variables in the with statement block, upon execution, check whether it has properties in a zhangsan.

We know that when you run a script, you need to do two things, first compile it and then execute it.
Obviously, at compile time, you can't be sure what properties the zhangsan variable represents. A zhangsan can only be determined to be an instance of a Person at execution time. So you can't tell at compile time whether the variable in the with block is a zhangsan property or a variable in the variable scope chain above.

This is consistent With strict mode checking whether a variable is defined at compile time, so strict mode does not allow exceptions to exist, so it is understandable that strict mode disables the With statement.


Related articles: