Node Modules - exporting a variable versus exporting functions that reference it?

前端 未结 3 2132
粉色の甜心
粉色の甜心 2021-02-09 05:48

Easiest to explain with code:

##### module.js
var count, incCount, setCount, showCount;
count = 0; 

showCount = function() {
 return console.log(count);
};
incC         


        
3条回答
  •  半阙折子戏
    2021-02-09 06:05

    In JavaScript, functions and objects (including arrays) are assigned to variables by reference, and strings and numbers are assigned by value--that is, by making a copy. If var a = 1 and var b = a and b++, a will still equal 1.

    On this line:

    exports.count = count; // let's also export the count variable itself
    

    you made a by-value copy of the count variable. The setCount(), incCount() and showCount() operations all operate on the count variable inside the closure, so m.count doesn't get touched again. If those variables were operating on this.count, then you'd get the behavior you expect--but you probably don't want to export the count variable anyway.

提交回复
热议问题