我从https://facebook.github.io/flux/docs/todo-list.html#content遇到了以下代码,并遇到了这个问题,因为该网站宣布
该对象(_todos)包含所有单独的待办事项。因为此变量位于类之外,但在模块的关闭之内,所以它保持私有状态-不能从模块外部直接更改。
这是真的?据我所知,似乎_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中,变量的作用域为模块。而且它不会成为全球性的(就像在浏览器上一样)。作为参考,请参阅此问题。
如果您使用browserify之类的东西,这仍然是正确的,因为从顶级角度来看,browserify使用立即调用的函数表达式来加载依赖关系(即模块)的映射,这些依赖关系基本上包装在具有自己作用域的函数中(而不是全局变量)。范围)。有关如何工作的更多信息,请参见此处。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句