Home  >  Article  >  Web Front-end  >  Understanding variable scope and memory issues in JavaScript

Understanding variable scope and memory issues in JavaScript

php是最好的语言
php是最好的语言Original
2018-08-03 10:17:571143browse

Variable scope and memory issues

1. Basic type and reference type values

The basic type is a simple data segment (5 value types), and the reference type is an object ( reference to the manipulated object).

1.1 Copying variable values

The reference type actually passes the function pointer when copying. After the copy is completed, the two variables actually reference the same heap memory. Object, if you change this object, the values ​​of the two variables will also change synchronously.

1.2 Passing parameters

The parameters of the function are all passed by value. In fact, I think this statement is somewhat abstract. It’s better to sum it up like this. When the variable passed to the function is a value type, the value of the original variable passed to the function will not change with the influence inside the function. When the variable passed to the function is a reference type (object), the reference of the original variable passed to the function will not change with the influence inside the function. In fact, it is not easy to understand here. For example, give an example to illustrate

        var obj = {
            name: 'andy'
        }

        function ChangeObj(val) {
            val.age = '25'
            val = {
                name:'zakas',
                age:40
            }
            return val;
        }
        ChangeObj(obj); // {name:'zakas',age:40}
        console.log(obj) // {name:'andy',age:25}

In the above example, the memory address of val in the function has changed (the reference has changed). If the function is passed by reference, then val's The reference is the reference of obj. If the application of val changes, the reference of obj will also change, so the result of obj should also be {name:'zakas',age:40}. If passed by value, obj is assigned to its reference to val, but their references are not associated together. Changes to the val reference will not affect the reference address of obj.

The formal parameters of a function are local variables in the function scope. It will be destroyed when the function is finished running.

1.3 Detection type

instanceof can perform more clear detection of reference types. Therefore, the value type in instanceof is always false, and there is no need to use its method to detect the value type. instanceof can only distinguish between Array Object and RegExp

2. Execution environment

Each execution environment has a variable object, and the concept of variable object is very important. It is a large collection of all variables defined in the scope; each execution environment has a variable object, which stores all the variables we define, but we cannot access this variable object, but it can be parsed It is used in the background when the server processes data.

    function A() {
        var tempA;
        function B() {
            var tempB;
            function C() {
                var tempC
            }
        }
    }

The scope chain of B() contains 3 objects, one is its own variable object, as well as A's variable object and the global variable object. The scope chain in A() contains 2 objects, one is A()'s own variable object, and the other is the global variable object. Therefore, A cannot access B's variables, but can only access its own and global variables. But B can not only access its own variables, but also access variables in A and the global scope.

2.1 Extend the scope chain

with

With is equivalent to creating a new variable object above the current scope. For example:

    var obj = {
        name:'andy',
        sex:'man',
        hobby:'game'
    }
    function fn() {
        with(obj) {
            fnName = name;
            fnSex = sex;
            fnHobby = hobby;
        }
        console.log(fnName,fnSex,fnHobby) // andy,man,game
    }
    fn()

With method will cause serious loss of performance, so it is generally not recommended to use

2.2 No block-level scope

You must know this concept, function and difference , the most common question:

for(var i =0 ; i < 10 ; i++ ) {
    setTimeout(function(){
        console.log(i);
    },0)
}

Under the premise of understanding this problem, you must first know that the timer is asynchronous. Even if it is 0, it must be placed in the cache area first. When other programs start from the top, Call it again after the execution is completed. So after other programs are executed from top to bottom, since there is no block-level scope, i is global and has become 10, so 10 10s are output. If i is changed to let with block-level scope, the problem will be solved.

for(let i =0 ; i < 10 ; i++ ) {
    setTimeout(function(){
        console.log(i);
    },0)
}

2.3 Garbage collection

JavaScript has an automatic garbage collection mechanism

The process of using values ​​is actually equivalent to allocating variables Write and read operations to the memory. JavaScript allocates memory during the process of creating variables, and automatically releases the variables when they are no longer used. This process is called a garbage collection mechanism, but this automaticity is the source of confusion. Many developers therefore feel that they do not need to care too much about memory issues, which is wrong.

Principle: The garbage processor will periodically detect by default, find out those unused variables, and then release its memory.
Recycling strategy: In the local environment, after the function is called, the garbage collector will track which variables are useful and which variables are useless. For useless variables, mark them to prepare for recycling their memory. , but the tag method usually has two other strategies:

  • Tag clearing: Since 2012, all browsers use the tag clearing method for garbage collection, and all js garbage The improvement of recycling is also based on the algorithm optimization of mark and clear method.

  • Reference counting: This is basically no longer used due to serious circular reference problems.

Therefore, when writing programs that occupy less memory is a very important point for high-performance pages. So when we write a program, once the data is no longer needed, it is best to set it to null to Dereference

Related articles:

JavaScript variable scope and memory Question (2)

Li Yanhui Javascript video tutorial

The above is the detailed content of Understanding variable scope and memory issues in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn