JavaScript With Statement Learning

Source: Internet
Author: User


Syntax format

With (object instance)
{
code block
}

Sometimes, I'm in a program code, many times you need to use an object's properties or methods, as before, are passed: Object. Property or object. method to obtain the object's properties and methods in such a way that it is a bit troublesome to learn the WITH statement, you can do this in a way similar to the following:

With (Objinstance)
{
var str = attribute 1;
.....
}

Remove the trouble of writing object names multiple times.


The WITH statement is deprecated in ECMAScript 5, and one of the main reasons is that it produces inexplicable side effects, such as:

var obj = {A:3};

With (obj) {
A = 7;
b = 5;
}

Here, we create a global variable B. But generally we think B is the attribute of the Obj object-unfortunately not, we did create a global variable.

We know that global variables are demons, especially the global variables that are inexplicably generated. So ECMAScript 5 to introduce ' use strict ', to solve such problems.

If we add the ' use strict ' before the code:

' Use strict ';
var obj = {A:3};

With (obj) {
b = 5;
}

This error is reported after the run:

Syntaxerror:strict mode code may isn't contain ' with ' statements

With is not allowed in strict mode. Well, that's not necessary.

Another reason for not having a with is that it slows down the speed of the code. Typically, the JavaScript engine makes a lot of optimizations for the JavaScript code to run, but the introduction of with (and eval) becomes a variable such as "Highbury", causing the engine to not optimize the code.
Simply put, JavaScript does not use with, now, later, there is no need.

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.