JavaScriptでオブジェクトとメソッドを作成するさまざまな方法を理解しようとしています。私は多くの記事、ブログ、stackoverflow の質問を読んできましたが、一般的な概念は理解できたと思います。しかし、小さな javascript ライブラリ (coffeescript で記述) に遭遇し、オブジェクトとメソッドを作成する方法に少し戸惑いました。
スニペットを含めましたが、必要に応じてinstafeed.jsで完全なスクリプトを見つけることができます。
コード:
(function() {
var Instafeed, root;
Instafeed = (function() {
function Instafeed(params) {
var option, value;
this.options = {
target: 'instafeed',
get: 'popular',
resolution: 'thumbnail',
sortBy: 'most-recent',
links: true,
limit: 15,
mock: false
};
if (typeof params === 'object') {
for (option in params) {
value = params[option];
this.options[option] = value;
}
}
}
Instafeed.prototype.run = function() {
var header, instanceName, script;
if (typeof this.options.clientId !== 'string') {
if (typeof this.options.accessToken !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if (typeof this.options.accessToken !== 'string') {
if (typeof this.options.clientId !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if ((this.options.before != null) && typeof this.options.before === 'function') {
this.options.before.call(this);
}
if (typeof document !== "undefined" && document !== null) {
script = document.createElement('script');
script.id = 'instafeed-fetcher';
script.src = this._buildUrl();
header = document.getElementsByTagName('head');
header[0].appendChild(script);
instanceName = "instafeedCache" + this.unique;
window[instanceName] = new Instafeed(this.options);
window[instanceName].unique = this.unique;
}
return true;
}
...
return Instafeed;
})();
root = typeof exports !== "undefined" && exports !== null ? exports : window;
root.Instafeed = Instafeed;
}).call(this);
次のことが理解できなくて困っています。
著者がすべてを でラップすることを好んだのはなぜ
(function(){...}).call(this);
ですか? グローバル変数の作成を避けるためでしょうか?.call(this)
スクリプトの最後の部分はどのような目的に役立ちますか?なぜ作成者は
root
変数を作成したのですか?次の行は何のためにありますか?root = typeof exports !== "undefined" && exports !== null ? exports : window; root.Instafeed = Instafeed;
これは、coffeescript でオブジェクトとメソッドを作成するための推奨される方法であるため、これがより良い方法の 1 つだと思います。しかし、次のバージョンに対するその利点は私を逃れます:
function Instafeed(params) {
...
}
Instafeed.prototype.run = function() {
...
}