Javascript - difference between namespace vs. closure?

前端 未结 3 447
无人共我
无人共我 2021-02-02 03:34

In Javascript, what\'s the difference between a namespace and a closure? They seem very similar to me.

EDIT

Specifically, this article discusses namesp

3条回答
  •  佛祖请我去吃肉
    2021-02-02 04:03

    A namespace is essentially an Object with no interesting properties that you shove stuff into so you don't have a bunch of variables with similar and/or conflicting names running around your scope. So, for example, something like

    MyNS = {}
    MyNS.x = 2
    MyNS.func = function() { return 7; }
    

    A closure is when a function 'retains' the values of variables that are not defined in it, even though those variables have gone out of scope. Take the following:

    function makeCounter() { 
       var x = 0;
       return function() { return x++; }
    }
    

    If I let c = makeCounter() and then repeatedly call c(), I'll get 0, 1, 2, 3, .... This is because the scope of the inner anonymous function that makeCounter defines 'closes' over x, so it has a reference to it even though x is out of scope.

    Notably, if I then do d = makeCounter(), d() will start counting from 0. This is because c and d get different instances of x.

提交回复
热议问题