Understanding closure in Javascript

后端 未结 8 658
不思量自难忘°
不思量自难忘° 2020-12-28 23:19

I\'m trying to wrap my head around closures in Javascript.

Here is an example from a tutorial:

function greeter(name, age) {
  var message = name + \         


        
8条回答
  •  隐瞒了意图╮
    2020-12-28 23:38

    A better example may be

    function add(start, increment) {
      return function() {
          return start += increment;
      }
    }
    
    var add1 = add(10, 1);
    
    alert(add1()); // 11
    alert(add1()); // 12
    

    Here, every time you call the returned function, you add 1. The internals are encapsulated.

    The returned function still has access to its parents variables (in this case, start and increment).

    On a lower level of thinking, I think it means that the function's stack is not destroyed when it returns.

提交回复
热议问题