美文网首页
module.exports和exports

module.exports和exports

作者: Allan要做活神仙 | 来源:发表于2017-03-31 11:42 被阅读14次
// 2.js
exports.id = 'exports的id';  
exports.id2 = 'exports的id2';  
exports.func = function(){  
    console.log('exports的函数');
};
exports.func2 = function() {  
    console.log('exports的函数2');
};
module.exports = {  
    id: 'module.exports的id',
    func:function(){
        console.log('module.exports的函数');
    }

};
// 3.js
var a = require('./2.js');  
// 当属性和函数在module.exports都有定义时:
console.log(a.id);  // module.exports的id  
console.log(a.func()); // module.exports的函数

// 当属性在module.exports没有定义,函数在module.exports有定义
console.log(a.id2);  // undefined  
console.log(a.func());  // module.exports的函数

// 当函数在module.exports没有定义,属性在module.exports有定义
console.log(a.id);        // module.exports的id  
console.log(a.func2());    // 报错了 TypeError: a.func2 is not a function  

由上得知
1.module.exports像是exports的大哥,当module.exports以{}整体导出时会覆盖exports的属性和方法,
2.注意,若只是将属性/方法挂载在module.exports./exports.上时,exports.id=1和module.exports.id=100,module.exports.id=function(){}和exports.id=function(){},最后id的值取决于exports.id和module.exports.id的顺序,谁在后,就是最后的值

相关文章

网友评论

      本文标题:module.exports和exports

      本文链接:https://www.haomeiwen.com/subject/zsnmottx.html