Home > Web Front-end > JS Tutorial > In-depth understanding of JavaScript scope and closure_Basic knowledge

In-depth understanding of JavaScript scope and closure_Basic knowledge

WBOY
Release: 2016-05-16 16:35:56
Original
1162 people have browsed it

Scope

Scope is the scope of a variable and function. All variables declared within a function in JavaScript are always visible within the function body. There are global scope and local scope in JavaScript, but there is no block-level scope, local scope Variables have higher priority than global variables. Let's use a few examples to understand the "hidden rules" of scope in JavaScript (these are also questions often asked in front-end interviews).

1. Declare variables in advance
Example 1:

var scope="global";
function scopeTest(){
  console.log(scope);
  var scope="local" 
}
scopeTest(); //undefined
Copy after login

The output here is undefined and no error is reported. This is because the declaration within the function we mentioned earlier is always visible in the function body. The above function is equivalent to:

var scope="global";
function scopeTest(){
  var scope;
  console.log(scope);
  scope="local" 
}
scopeTest(); //local
Copy after login

Note that if you forget var, the variable will be declared as a global variable.

2. No block-level scope

Unlike other commonly used languages, there is no block-level scope in Javascript:

function scopeTest() {
  var scope = {};
  if (scope instanceof Object) {
    var j = 1;
    for (var i = 0; i < 10; i++) {
      //console.log(i);
    }
    console.log(i); //输出10
  }
  console.log(j);//输出1

}

Copy after login

The scope of variables in JavaScript is function-level, that is, all variables in the function are defined throughout the function. This also brings some "hidden rules" that we will encounter if we don't pay attention:

var scope = "hello";
function scopeTest() {
  console.log(scope);//①
  var scope = "no";
  console.log(scope);//②
}
Copy after login

The value output at ① turned out to be undefined, which is crazy. We have already defined the value of the global variable. Shouldn't this place be hello? In fact, the above code is equivalent to:

var scope = "hello";
function scopeTest() {
  var scope;
  console.log(scope);//①
  scope = "no";
  console.log(scope);//②
}
Copy after login

Declare in advance and global variables have lower priority than local variables. According to these two rules, it is not difficult to understand why undefined is output.

Scope chain

In JavaScript, each function has its own execution context. When the code is executed in this environment, a scope chain of variable objects will be created. The scope chain is a list of objects or an object chain, which ensures Ordered access to variable objects.
The front end of the scope chain is the variable object of the current code execution environment, which is often called the "active object". The search for variables will start from the object of the first chain. If the object contains variable attributes, then the search will stop. If If not, it will continue to search up the upper scope chain until it finds the global object:

The step-by-step search of the scope chain will also affect the performance of the program. The longer the variable scope chain, the greater the impact on performance. This is one of the main reasons why we try to avoid using global variables.

Closure

Basic concepts
Scope is a prerequisite for understanding closures. Closures mean that variables in the external scope can always be accessed within the current scope.

function createClosure(){
  var name = "jack";
  return {
    setStr:function(){
      name = "rose";
    },
    getStr:function(){
      return name + ":hello";
    }
  }
}
var builder = new createClosure();
builder.setStr();
console.log(builder.getStr()); //rose:hello
Copy after login

The above example returns two closures in the function. Both closures maintain references to the external scope, so variables in the external function can always be accessed no matter where they are called. A function defined inside a function will add the active object of the external function to its own scope chain. Therefore, in the above example, the properties of the external function can be accessed through the internal function. This is also a way for JavaScript to simulate private variables.

Note: Since closures will have additional function scopes (internal anonymous functions carry the scope of external functions), closures will take up more memory space than other functions. Excessive use may lead to memory usage. increase.

Variables in closures

When using a closure, due to the influence of the scope chain mechanism, the closure can only obtain the last value of the internal function. A side effect of this is that if the internal function is in a loop, the value of the variable is always the last value. a value.

  //该实例不太合理,有一定延迟因素,此处主要为了说明闭包循环中存在的问题
  function timeManage() {
    for (var i = 0; i < 5; i++) {
      setTimeout(function() {
        console.log(i);
      },1000)
    };
  }
Copy after login

The above program does not input the numbers 1-5 as we expected, but outputs 5 all 5 times. Let’s look at another example:

function createClosure(){
  var result = [];
  for (var i = 0; i < 5; i++) {
    result[i] = function(){
      return i;
    }
  }
  return result;
}
Copy after login

The return value of calling createClosure()[0]() is 5, and the return value of createClosure()[4]() is still 5. Through the above two examples, we can see the problems that closures have when using internal functions with loops: because the scope chain of each function stores active objects for external functions (timeManage, createClosure), therefore, they They all refer to the same variable i. When the external function returns, the value of i at this time is 5, so the value of each internal function i is also 5.
So how to solve this problem? We can force the expected result to be returned via an anonymous wrapper (anonymous self-executing function expression):

function timeManage() {
  for (var i = 0; i < 5; i++) {
    (function(num) {
      setTimeout(function() {
        console.log(num);
      }, 1000);
    })(i);
  }
}
Copy after login

Or return an anonymous function assignment in the closure anonymous function:

function timeManage() {
  for (var i = 0; i < 10; i++) {
    setTimeout((function(e) {
      return function() {
        console.log(e);
      }
    })(i), 1000)
  }
}
//timeManager();输出1,2,3,4,5
function createClosure() {
  var result = [];
  for (var i = 0; i < 5; i++) {
    result[i] = function(num) {
      return function() {
        console.log(num);
      }
    }(i);
  }
  return result;
}
//createClosure()[1]()输出1;createClosure()[2]()输出2
Copy after login

无论是匿名包裹器还是通过嵌套匿名函数的方式,原理上都是由于函数是按值传递,因此会将变量i的值复制给实参num,在匿名函数的内部又创建了一个用于返回num的匿名函数,这样每个函数都有了一个num的副本,互不影响了。

闭包中的this

在闭包中使用this时要特别注意,稍微不慎可能会引起问题。通常我们理解this对象是运行时基于函数绑定的,全局函数中this对象就是window对象,而当函数作为对象中的一个方法调用时,this等于这个对象(TODO 关于this做一次整理)。由于匿名函数的作用域是全局性的,因此闭包的this通常指向全局对象window:

var scope = "global";
var object = {
  scope:"local",
  getScope:function(){
    return function(){
      return this.scope;
    }
  }
}
Copy after login

调用object.getScope()()返回值为global而不是我们预期的local,前面我们说过闭包中内部匿名函数会携带外部函数的作用域,那为什么没有取得外部函数的this呢?每个函数在被调用时,都会自动创建this和arguments,内部匿名函数在查找时,搜索到活跃对象中存在我们想要的变量,因此停止向外部函数中的查找,也就永远不可能直接访问外部函数中的变量了。总之,在闭包中函数作为某个对象的方法调用时,要特别注意,该方法内部匿名函数的this指向的是全局变量。

幸运的是我们可以很简单的解决这个问题,只需要把外部函数作用域的this存放到一个闭包能访问的变量里面即可:

var scope = "global";
var object = {
  scope:"local",
  getScope:function(){
    var that = this;
    return function(){
      return that.scope;
    }
  }
}
object.getScope()()返回值为local。

Copy after login

内存与性能

由于闭包中包含与函数运行期上下文相同的作用域链引用,因此,会产生一定的负面作用,当函数中活跃对象和运行期上下文销毁时,由于必要仍存在对活跃对象的引用,导致活跃对象无法销毁,这意味着闭包比普通函数占用更多的内存空间,在IE浏览器下还可能会导致内存泄漏的问题,如下:

 function bindEvent(){
  var target = document.getElementById("elem");
  target.onclick = function(){
    console.log(target.name);
  }
 }
Copy after login

上面例子中匿名函数对外部对象target产生一个引用,只要是匿名函数存在,这个引用就不会消失,外部函数的target对象也不会被销毁,这就产生了一个循环引用。解决方案是通过创建target.name副本减少对外部变量的循环引用以及手动重置对象:

 function bindEvent(){
  var target = document.getElementById("elem");
  var name = target.name;
  target.onclick = function(){
    console.log(name);
  }
  target = null;
 }
Copy after login

闭包中如果存在对外部变量的访问,无疑增加了标识符的查找路径,在一定的情况下,这也会造成性能方面的损失。解决此类问题的办法我们前面也曾提到过:尽量将外部变量存入到局部变量中,减少作用域链的查找长度。

总结:闭包不是javascript独有的特性,但是在javascript中有其独特的表现形式,使用闭包我们可以在javascript中定义一些私有变量,甚至模仿出块级作用域,但闭包在使用过程中,存在的问题我们也需要了解,这样才能避免不必要问题的出现。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template