关于node.js export 的问题

main.js

var fooExports = require('./foo')
console.log(fooExports.foo)
console.log(fooExports)

foo.js

var foo = 'bar'

function add(x, y) {
  return x + y
}

module.exports.foo = '挂载:hello'

module.exports = 'hello' 


module.exports = function (x, y) {   
  return x + y
}

module.exports = {  
    return x + y
  },
  str: 'hello'
}

//module.exports.foo = '挂载:hello'

执行结果:

undefined
{ add: [Function: add], str: 'hello' }

main.js

var fooExports = require('./foo')
console.log(fooExports.foo)
console.log(fooExports)

foo.js

var foo = 'bar'

function add(x, y) {
  return x + y
}

module.exports.foo = '挂载:hello'

module.exports = 'hello' 


module.exports = function (x, y) {   
  return x + y
}

module.exports = {  
    return x + y
  },
  str: 'hello'
}

module.exports.foo = '挂载:hello'

执行结果:

挂载:hello
{ add: [Function: add], str: 'hello', foo: '挂载:hello' }

为什么第一次执行结果会出现 undefined?

上面的module.exports被定义多次(多次赋值),那么就以最后的一次为准