嗨,我發現framework他們在這裏使用了很多這種模式。節點js中的exports.install是什麼?
exports.install = function(){
//code
}
但通常你看到這個模式中的NodeJS
module.exports = {
//code
}
這是同樣的事情,或者這是什麼東西?
嗨,我發現framework他們在這裏使用了很多這種模式。節點js中的exports.install是什麼?
exports.install = function(){
//code
}
但通常你看到這個模式中的NodeJS
module.exports = {
//code
}
這是同樣的事情,或者這是什麼東西?
exports
是對應於module.exports
之前的任何對象。我認爲這是由於一些遺留代碼造成的,但基本上人們使用module.exports
如果他們想用自己的對象或函數替換整個對象,而如果他們只想從模塊中掛起函數,則使用exports
。這是一個有點混亂在第一,但本質上exports.install
只是意味着調用代碼會做這樣的事情:
const mod = require('that-module');
mod.install(params, callback); // call that function
你看這個框架可能是使用它作爲一個引導過程的一部分,據我所知它不對節點引擎本身具有重要意義。
是的,這是一回事。您可以使用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 !
所以,它只是開發者的風格。