[Front-end development]] var js in writing and do not write difference

var js in with no difference between the

When you declare a variable in Javascript, although not with the var keyword to declare and keyword statement, a lot of time running and there is no problem, but this is still a difference in two ways. Code can run normally does not represent a suitable code.

var num = 1;

Declaring a variable in the current domain, if declared in a method, compared with the local variable (local variable);. If the field is a global statement, are global variables.

And num = 1;

In fact, attribute assignment. First, it tries to resolve num in the current scope chain (as declared in a method, the current scope chain represents the global scope and methods of the local scope etc ...); if found in any current scope chain num will perform on the property assignment num; num If not found, it will be in the global object (ie, the current scope chain of the most top-level object, such as a window object) to create and assign attributes num.

note! It does not declare a global variable, but creates a property of the global object.

Even so, you still may be difficult to understand where the difference between "variable declaration" with "create object properties." In fact, Javascript variable declarations, and create properties in each Javascript Each attribute has a certain labeled to indicate their properties ---- such as read-only (ReadOnly) non-enumerable (DontEnum) can not be deleted (DontDelete), etc. Wait.

Since the variable declaration comes not delete properties var num = 1 with Comparative num = 1, the former is a variable declared with attributes can not be deleted, and therefore can not be deleted; the latter is a property of global variables, global variables can be removed from the


For more details, see the following code:
// global variable num1, num2 as an attribute of the window  
                      var. 1 = num1; 
                      num2 = 2; 
                      // Delete num1; not delete 
                      // delete num2; delete 
                      function Model () { 
                             var. 1 = num1; // local variable 
                             num2 = 2; // window attribute 
                             // anonymous function 
                             (function () { 
                                    var = NUM. 1; // local variable 
                                    num1 = 2; // inherited scope (closure) 
                                    num3 =. 3; // window attribute 
                             } ()) 
                      }
 

PS. In ECMAScript5 standard, there is a "strict mode" (Strict Mode). In strict mode for undeclared identifier assignment will throw misquoted, it is possible to prevent the accidental creation of a global variable attributes. At present, some new version of the browser already support.

Guess you like

Origin www.cnblogs.com/xiaohuizhang/p/11755737.html