我在 StackOverflow 上找到的问题都没有回答此问题或为我的问题提供解决方案。
我正在创建一个应用程序来使用 Spotify 的 API。我对 JavaScript 比较陌生,但我已经在其他语言(特别是 OO 语言)中担任了很长时间的程序员。我正在尝试在我的项目中使用 OO 式的代码来处理 API。
我可能不太明白如何做,但这是我的基本理解。
我将处理 API 的所有代码都放在一个名为 smartspot.js
的文件中。该文件的内部类似于以下内容。
/**
* Taps into the Spotify API to create a playlist with top songs from artists most like a certain artist.
* @param {string} _clientId the client ID code given to the user by Spotify.
* @param {string} _clientSecret the client secret code given to the user by Spotify.
* @param {string} _redirectUri a Redirect URI that has been white-listed by Spotify.
* @constructor creates a SmartSpot that can access the Spotify API.
*/
function SmartSpot(_clientId, _clientSecret, _redirectUri)
{
//initialize the variables (omitted)
var clientId = _clientId;
clientSecret = _clientSecret;
//etc...
//various irrelevant variables and functions are ommited.
this.foo = function(param)
{
//does stuff
};
//etc...
}
现在,我相信 function SmartSpot(_clientId, _clientSecret, _redirectUri)
是一个构造函数(就像在 Java 和 C++ 等语言中一样)。如果我错了请纠正我。因此,假设它是一个构造函数,我需要在另一个文件中使用它:我的 Express“routes”文件。它位于“routes/index.js”中。
我把这个放在文件的顶部
var SmartSpot = require('../SmartSpot'); //I have also tried require('../Smartspot.js');
//later on
var smartSpot = new SmartSpot(clientId, clientSecret, redirectUri);
//elsewhere
smartSpot.foo();
但是,编译器向我提示:
TypeError: SmartSpot is not a function
at Object.<anonymous>
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
//etc...
我在这里缺少什么?我使用 IntelliJ 来完成这一切,它建议我需要创建一个函数,所以我这样做了,它在 index.js
文件中创建了构造函数/函数。我想将文件分开以使代码更容易理解并且更易于使用。
如果您需要回答我遗漏的这个问题,请告诉我。
最佳答案
感谢 Alexander Max 的帮助,环顾四周后,我注意到我的很多其他文件都有 module.exports = Something;
。
事实证明这是解决方案。我将 module.exports = SmartSpot;
放在 SmartSpot.js
文件的底部,并放置 var SmartSpot = require('../SmartSpot') ;
在另一个文件的顶部。现在,该文件已被正确解释,我可以从我的路由文件中使用它的功能。
关于javascript - 如何使用 require() 使用另一个文件中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511508/