Understanding closure in Javascript

后端 未结 8 705
不思量自难忘°
不思量自难忘° 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:58

    I don't think this is a good example for private variables, because there are no real variables. The closure part is that the function greet can see message (which is not visible to the outside, hence private), but it (or anyone else) is not changing it, so it is more of a constant.

    How about the following example instead?

    function make_counter(){
        var i =0;
        return function(){
            return ++i;
        }
    }
    
    var a = make_counter();
    console.log(a());  // 1
    console.log(a());  // 2
    var b = make_counter();
    console.log(b());  // 1
    console.log(a());  // 3
    

提交回复
热议问题