JavaScript Strict mode disables the With statement reason _javascript tips

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.