0
StackOverflowで見つけた質問は、この質問に答えたり、私の問題を解決しました。require()を使用して別のファイルから関数を使用する方法
私はSpotifyのAPIを使用するためのアプリを作成しています。私はJavaScriptに比較的新しいですが、私は長い間、他の言語、特にOO言語のコーダーでした。私は、APIを扱うために私のプロジェクトでオブジェクト指向のコードを使用しようとしています。
私はこれを行う方法を正しく理解していないかもしれませんが、ここでは私の基本的な理解です。 APIを扱うためのコードはすべてsmartspot.js
という1つのファイルにあります。そのファイルの中には、次のようなものがあります。
/**
* 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++などの言語のように)コンストラクタであると信じています。私が間違っているなら、私を訂正してください。それで、がコンストラクタであると仮定すると、別のファイルで使用する必要があります。私の明示的な "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
ファイルにコンストラクタ/関数を作成します。私はファイルを分けて、コードを理解しやすくし、使いやすくしたいと思っています。
私が残したこの質問に答える必要があるものがあれば、教えてください。
これらのJavaScriptファイルをHTMLページで使用しますか?はいの場合は、