如果 javascript 变量位于 class 之外,但在模块的闭包内,它是私有的吗?

If a javascript variable lives outside the class, but within the closure of the module, is it private?

我从 https://facebook.github.io/flux/docs/todo-list.html#content 中看到以下代码,并有这个问题,因为该网站声明

This object (_todos) contains all the individual to-do items. Because this variable lives outside the class, but within the closure of the module, it remains private — it cannot be directly changed from outside of the module.

这是真的吗?据我所知, _todos 似乎是一个全局对象。

var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('events').EventEmitter;
var TodoConstants = require('../constants/TodoConstants');
var assign = require('object-assign');

var CHANGE_EVENT = 'change';

var _todos = {}; // collection of todo items

/**
 * Create a TODO item.
 * @param {string} text The content of the TODO
 */
function create(text) {
  // Using the current timestamp in place of a real id.
  var id = Date.now();
  _todos[id] = {
    id: id,
    complete: false,
    text: text
  };
}

/**
 * Delete a TODO item.
 * @param {string} id
 */
function destroy(id) {
  delete _todos[id];
}

var TodoStore = assign({}, EventEmitter.prototype, {

  /**
   * Get the entire collection of TODOs.
   * @return {object}
   */
  getAll: function() {
    return _todos;
  },

  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },

      dispatcherIndex: AppDispatcher.register(function(payload) {
        var action = payload.action;
        var text;

        switch(action.actionType) {
          case TodoConstants.TODO_CREATE:
            text = action.text.trim();
            if (text !== '') {
              create(text);
              TodoStore.emitChange();
            }
            break;

          case TodoConstants.TODO_DESTROY:
            destroy(action.id);
            TodoStore.emitChange();
            break;

          // add more cases for other actionTypes, like TODO_UPDATE, etc.
        }

        return true; // No errors. Needed by promise in Dispatcher.
      })

})    ;

module.exports = TodoStore;

是的,这是真的。

在您的示例中,_todos 的范围仅限于模块(即文件)本身,而不是全局的。

在 node.js 中,变量的范围仅限于模块。而且它不会成为全球性的(就像在浏览器上一样)。有关参考,请参阅 this question

如果你使用 browserify this is still true because from a top level perspective browserify uses an immediately invoked function expression to load in a mapping of dependencies (i.e modules) which are basically wrapped in a function that has it's own scope (NOT the global scope). More information on how that works can be found here.