JS Variables and scopes

Source: Internet
Author: User

1. Values of the base type and reference type

In JS, a variable may contain values for two different data types, a base type value, and a reference type value. A primitive type value refers to a simple data segment, whereas a reference type value refers to an object that may consist of multiple values.

1.1. Dynamic Properties

Defining a base type value and a reference type is a worthwhile way to create a variable and assign a value to the variable. However, when this value is saved to a variable, the actions that can be performed on different types of values, for reference type values, can be added to the property and method. You can also change and delete its properties and methods.

var person = new Object ();p erson.name = ' Tom '; alert (person.name)//tom 

The above code we created an object and saved it in the person, then we added a Name property to the object and assigned the value of the string to this property, which is accessed through the alert function.

This property will persist if the object is not destroyed or if the property is not deleted.

var name = ' Test '; test.name = ' admin '; alert (test.name)//undefined 

In the above example, when we define a basic variable, we define a new attribute for name and assign the value to admin. However, when accessing this property, it is found that the property is missing, which means that the property can only be added dynamically to the reference type value.

1.2. Copy Variable type

In addition to the way it is saved, there is a difference when copying the base type and reference type values from one variable to another, and if you copy the value of the base type from one variable to another, a new value is created on the variable object. The value is then copied to the location assigned to the new variable.

var num = 5; var num2 = num;

In this case, the value saved in Num is 5, and num2 also holds the value 5 when NUM is used to initialize num2, but 5 in num2 and 5 o'clock in Num are completely independent, which is only one copy of the NUM value, after which the two variables can participate in any operation without any effect

When a value of a reference type is copied from one variable to another, the value stored in the variable object is also copied into the space allocated for the new variable, but the worthy copy is actually a pointer to an object stored in the heap, and after the copy operation is finished, Two variables will actually refer to the same object, so changing one of the variables will affect the other variable.

var obj1 = new Object (), var obj2 = obj1;obj1.name = ' test '; alert (obj2.name);//test  

1.3. Passing parameters

The parameters of all functions in ECMAScript are passed by value, that is, copying the values outside the function to the parameters inside the function, and copying the value from one variable to another, the basic type value is passed as if the basic variable is copied, and the reference type is worth passing. Is the same as a copy of a reference type variable.

When you pass a value of a primitive type to a parameter, the passed value is copied to a local variable (named argument, which is an element in the arguments object), and the value in memory is copied to a local variable when it is worthwhile to pass the reference type to the parameter. So the variation of this local variable will be reflected in the outside of the function.

function Addten (num) {    num + =ten    ; return num;  } var count =Addten; var result = N (count); alert (count)//20alert (result)//30    

This function has a parameter num, and the argument is actually a local variable of the function, when the function is called, the variable count is passed as a parameter to the function, the value is 20, then the value 20 is assigned to the parameter num, and within the function, the value of the parameter num is added 10, However, this change does not affect the count outside the function, the parameter num and the parameter count are not mutually exclusive, they only have the same value, if NUM is passed by reference, then the value of the variable will also become 30, thus reflecting the changes inside the function.

function  setName (obj) {  obj.name = ' admin ';} var person = new Object (), setName (person), alert (person.name),//admin  

In the above code, an object is created and saved in person, and then the object is passed to the SetName () function and assigned to obj, within which obj and person refer to the same object, in other words, even if the object is passed by value, OBJ also accesses the same object by reference, so when you add the Name property to obj inside the function, the person outside the function will react. Because the object pointed to by person has only one in heap memory and is a global object.

function setName (obj) {  obj.name = ' admin ';  obj = new Object ();  Obj.name = ' Gray '}var person = new Object (), setName (person); alert (person.name)//admin    

1.4. Detection type

Although TypeOf is a very powerful helper when detecting a basic data type (typeof (NULL) is object) but when detecting the value of a reference type, the operator is not very useful, and usually we don't want to know if a value is an object, but rather what type of object it is, Provides the instanceof operator

If the variable is an instance of a given reference type, then the instanceof operator returns true

Alert (person instanceof Object);  The variable person is an object alert (colors Instanceof object); Is it an array? alert (Pattren instanceof REGEXP); Is it regexp?

As a rule, the reference type is an instance of object.

2 Execution Environment and scope

The execution environment defines other data that a variable or function has access to, and each execution environment has a variable object associated with it, and all variables and functions defined in the environment are stored in the object. The global execution environment is the outermost execution environment in which the global execution environment is considered a Windows object, so all global variables and functions are created as properties and methods of the Window object, and after all code in an execution environment is executed, the environment is destroyed. The variables and functions stored in them will also be destroyed. (The global environment will not be destroyed until the application exits, such as by closing the Web page or browser)

Each function has its own execution environment, and when the execution flow enters a function, the environment of the function is pushed into an environment stack, and after the function executes, the stack ejects its environment and returns control to the previous execution environment.

When code executes in an environment, a scope chain of variable objects is created, and the purpose of the scope chain is to guarantee orderly access to all variables and functions that the execution environment has access to. The front end of the scope chain, which is always the environment variable in which the code is currently executing. If the environment is a function, its active object is used as a variable object. The active object contains only one variable at the beginning, the arguments object, which does not exist in the global environment, the next variable object in the scope chain is from the containing (external) environment, and the next variable object is from the next containing object, thus continuing to the global execution environment. The variable object for the global execution environment is always the last object in the scope chain.

var color = ' Blue '; function ChangeColor () {   if (color = = ' Blue ') {        color = ' red ' ;       } else { C8/>color = ' Blue ';}} ChangeColor (); alert (' Color is now ' + color)//color      are now red

In this simple example, the scope chain of the function ChangeColor () contains two objects, its own variable object, and the variable object of the global environment, which can access the variable color inside the function, because it can be found in the scope chain. In addition, variables defined in the local scope can be used interchangeably in the local environment and in the Global environment

var color = ' Blue '; function ChangeColor () {    var anthorcolor = ' Red ';    Anthorcolor = color;    function Swapcolor () {        var tempcolor = anthorcolor; anthorcolor = color; color = Swapcolor ()}// Only Colorchangecolor () can be accessed here       

The above code involves 3 execution environment, Global environment, local environment of ChangeColor (), Local Environment of Swapcolor (), Global environment has a variable color and a function changecolor (), ChangeColor () The local environment has a variable named Anthorcolor and a function of Swapcolor (), but it can also access variables in the global variable Color,swapcolor () in the local environment there is a variable tempcolor (), This variable can only be accessed in this environment, and the local environment, whether global or changecolor (), cannot be accessed, however, within swapcolor (), you can access all the variables in the other two environments, because those two environments are its parent execution environment

As shown, the internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions in the internal environment. The linkages between these environments are linear and sequential. Each environment can search up the scope chain. To query for variables and function names. However, no environment can enter another execution environment by searching the scope chain down.

2.1. Extend the scope chain

Although there are only two types of execution environments, global and local (functions), there are other ways to extend the scope chain. That's because some statements can temporarily add a variable object to the front of the scope chain, which is removed after the code executes. Specifically, the scope chain is extended when the execution stream enters any of the following statements

Catch block for Try-catch statements

With statement

Both statements will add a variable object at the front of the scope chain

2.2. No block-level scopes

In other classes of C, code enclosed in curly braces has its own scope (in JS, it is the execution environment),

if (True) {    var color = ' Blue '}alert (color)//blue 

As above, if it is in c,c++, or Java, color will be destroyed when the if execution is complete, but in JS, the variable declaration in the IF statement will add the variable to the current execution environment (here is the Global environment) in the use for especially remember this

for (var i = 0;i<10;i++) {     dosomething (i)  }alert (i)//10

For a block-scoped language, the variable defined for the For statement only exists in the loop environment, but in JS, the variable I created for the for statement still exists in the execution environment outside the loop after the loop ends.

declaring variables

Variables declared with Var are automatically added to the nearest environment, and within the function, the closest environment is the local environment of the function.

function(num1,num2) {    var sum = num1 + num2;    return sum;} var result = Add (10,20)//30alert (sum)//The error occurs because the sum is not a valid variable  

In the above function, if you omit the var keyword from the example, sum can also be accessed when the Add () function finishes executing

function(num1,num2) {    sum = num1 + num2;    return sum;} var result = Add (10,20)//30alert (sum)//30  

The variable sum is not initialized with the keyword Var, so when you play add (), the sum added to the global environment continues to exist.

JS Variables and scopes

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.