模块化解决了JavaScript作用域互相污染问题,这里以写一个学校小例子,便于理解node的这个写法和一些简单的API(比如forEach这个.....)。
文件:
依次student.js,teacher.js,kclass.js(class为保留字,不能命名),index.js,school.js
function add(student) { console.log('Add student:' + student) } exports.add = add
function add(teacher) { console.log('Add teacher:' + teacher) } exports.add = add
var student = require('./student') var teacher = require('./teacher') function add(teacherName, students) { teacher.add(teacherName) students.forEach(function(item, index) { student.add(item) }) } exports.add = add
var kclass = require('./kclass') exports.add = function(kclasses) { kclasses.forEach(function(item,index) { var _klass = item var teacherName = item.teacherName var students = item.students kclass.add(teacherName, students) }) }
var school = require('./index.js') var classesArr = [ { 'teacherName':'Bob', 'students':['SB1','SB2'] } ]; school.add(classesArr);