官术网_书友最值得收藏!

  • MEAN Web Development
  • Amos Q. Haviv
  • 311字
  • 2021-08-05 17:46:46

JavaScript closures

Closures are functions that refer to variables from their parent environment. Using the closure pattern enables variables from the parent() function to remain bound to the closure. Let's take a look at the following example:

function parent() {
    var message = "Hello World";

    function child() {
        alert (message);
    }

    child();
}

parent();

In the preceding example, you can see how the child() function has access to a variable defined in the parent() function. But this is a simple example, so let's see a more interesting one:

function parent() {
   var message = 'Hello World';
    
  function child() {
    alert (message);
   }

   return child;
}

var childFN = parent()
childFN();

This time, the parent() function returned the child() function, and the child() function is called after the parent() function has already been executed. This is counterintuitive to some developers because usually the parent() function's local variables should only exist while the function is being executed. This is what closures are all about! A closure is not only the function, but also the environment in which the function was created. In this case, the childFN() is a closure object that consists of the child() function and the environment variables that existed when the closure was created, including the message variable.

Closures are very important in asynchronous programming because JavaScript functions are first-class objects that can be passed as arguments to other functions. This means that you can create a callback function and pass it as an argument to an event handler. When the event will be emitted, the function will be invoked, and it will be able to manipulate any variable that existed when the callback function was created even if its parent function was already executed. This means that using the closure pattern will help you utilize event-driven programming without the need to pass the scope state to the event handler.

主站蜘蛛池模板: 辽宁省| 建德市| 澎湖县| 陵水| 邳州市| 巴林左旗| 白银市| 即墨市| 应城市| 三亚市| 青神县| 中宁县| 民乐县| 石楼县| 论坛| 额济纳旗| 涡阳县| 高州市| 扎囊县| 昌平区| 玛曲县| 屯留县| 平利县| 翁源县| 舒城县| 定州市| 会泽县| 宁远县| 定襄县| 弥渡县| 抚州市| 大同市| 达州市| 鲁甸县| 威信县| 卓资县| 鲁山县| 濉溪县| 石屏县| 丽水市| 会宁县|