Closures in JS, Python

Posted on October 2, 2021
Tags: javascript

1 Closures is Class

var makeCounter = function() {
  //Private variable and functions START
  var privateCounter = 0;
  function privateChangeBy(val) {
    privateCounter += val;
  }
  //Private variable and functions END
  
  //Public variable and functions START
  return { 
    increment: function() {
      privateChangeBy(1);
    },

    decrement: function() {
      privateChangeBy(-1);
    },

    value: function() {
      return privateCounter;
    }
  }
  //Public variable and functions END
};

var newCounter = makeCounter() //similar to constructor
newCounter.increment() 
newCounter.value() //output 1
class makeCounter{
    private privateCounter;
    private privateChangeBy(val){...};
    public increment();
    public decrement();
    public value();
}

2 Closure in python vs JS

def f():
    a=0
    def g():
        a+=1 #ERRor
        print(a)
    return g
g=f()
g()
def f():
    a=0
    def g():
        nonlocal a
        a+=1 
        print(a)
    return g
g=f()
g()
let f=()=>{
    let a=0
    let g=()=>{
        a+=1
        console.log(a)
        
    }
    return g
    
}
let g=f()
g()

3 Closure and Scope

(define myenv
  ((λ (x)
     (λ (y) (+ x y)) )
   2))