2016-07-28 127 views

回答

1

exports是对应于module.exports之前的任何对象。我认为这是由于一些遗留代码造成的,但基本上人们使用module.exports如果他们想用自己的对象或函数替换整个对象,而如果他们只想从模块中挂起函数,则使用exports。这是一个有点混乱在第一,但本质上exports.install只是意味着调用代码会做这样的事情:

const mod = require('that-module'); 
mod.install(params, callback); // call that function 

你看这个框架可能是使用它作为一个引导过程的一部分,据我所知它不对节点引擎本身具有重要意义。

0

是的,这是一回事。您可以使用2种方式之一来设置您的代码。

不同的是memory。他们指向相同的记忆。你可以认为exports像一个变量,你不能用这种方式来导出模块:

鉴于此模块:

// test.js 
exports = { 
    // you can not use this way to export module. 
    // because at this time, `exports` points to another memory region 
    // and it did not lie on same memory with `module.exports` 
    sayHello: function() { 
     console.log("Hello !"); 
    } 
} 

下面的代码将得到错误:TypeError: test.sayHello is not a function

// app.js 
var test = require("./test"); 
test.sayHello(); 
// You will get TypeError: test.sayHello is not a function 

您必须使用module.exports导出模块的正确方法:

// test.js 
module.exports = { 
    // you can not use this way to export module. 
    sayHello: function() { 
     console.log("Hello !"); 
    } 
} 

// app.js 
var test = require("./test"); 
test.sayHello(); 
// Console prints: Hello ! 

所以,它只是开发者的风格。