我是从
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.
})
});上面写着
在上面的代码中有几件重要的事情要注意。首先,我们维护一个名为_todos的私有数据结构。此对象包含所有单独的待办事项。是因为这个变量存在于类之外,但是在模块的闭包中,它仍然是私有的--不能直接从模块外部更改它。这使我们无法在不使用操作的情况下更新存储,从而帮助我们为数据流保留一个独特的输入/输出接口。
在我看来,大胆的部分还不清楚。如何让js解释器知道所有这些代码都在模块闭包中,而不是在全局范围内?模块闭包从哪里开始,从哪里结束?
就我所知道
用var声明的变量的作用域是它当前的执行上下文,它要么是封闭函数,要么是任何函数之外声明的变量的,即全局。
有什么解释吗?
发布于 2016-02-11 14:49:18
您实际上遗漏了您引用的摘录中的最后一行:
module.exports = TodoStore;CommonJS是一个API,用于定义使用以下约定的模块:
require,允许它导入其他模块。module可供模块使用,以便它可以设置其exports属性来定义模块应该导出的内容;您在模块a.js中为module.exports设置的值正是require('./a')将返回的值。实现CommonJS的每个JS环境都必须知道这些规则。当然,这包括Node.js,但也包括像Browserify和Webpack这样的捆绑器,它们将打包您的代码,以使这些约定得到尊重。
这样,您就可以控制模块的哪一部分将被导出。
P.S.:请注意,您也可以使用exports变量来定义导出,并且它的使用与module.exports略有不同。详细信息请参见这个StackOverflow问题和答案
发布于 2017-05-11 03:57:25
通用JS模式使用构造函数来定义实用程序。
它是以类的形式定义的。
var moduleName = function() {
// private variables
// public functions
this.method1 = function() {
// logic1 goes here
};
this.method2 = function() {
// logic2 goes here
};
};所以我们将使用以下方法将类导出到其他模块
module.exports = moduleName;这样,其他模块就可以导入它,实例化它,然后使用该功能。
怎么用?
var module = require('moduleName'); //importing the module created above在这里,模块定义被获取、执行,然后在“模块”变量中可用。
这个变量名可以是任何内容。
var objectOfModule = new module(); //instance is created
objectOfModule .method1(); //use1
console.log(objectOfModule .method2()); //use2谢谢。
https://stackoverflow.com/questions/35342139
复制相似问题