返回

闭包之数

前端

In mathematics, a closure is a function that has access to the inner scope of another function, even after the outer function has returned. This can be useful for creating private variables and methods, or for creating functions that can access data from a parent scope.

In JavaScript, closures are created by nesting functions. The inner function has access to all of the variables and parameters of the outer function, even after the outer function has returned. This can be useful for creating private variables and methods, or for creating functions that can access data from a parent scope.

For example, the following code creates a closure that returns a function that adds two numbers:

function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}

The makeAdder function takes one argument, x, and returns a function that takes one argument, y, and returns the sum of x and y. The inner function has access to the variable x, even though the outer function has already returned.

Closures can also be used to create private variables and methods. For example, the following code creates a closure that defines a private variable named x and a private method named add:

function makeCounter() {
  let _x = 0;

  function _add(y) {
    _x += y;
  }

  return {
    increment: _add,
    getValue: function() {
      return _x;
    }
  };
}

The makeCounter function returns an object with two methods, increment and getValue. The increment method calls the add method to increment the value of x. The getValue method returns the value of x.

Closures are a powerful tool that can be used to create complex and reusable code. They can be used to create private variables and methods, or to create functions that can access data from a parent scope.