「JavaScriptライブラリを作成する」方法を先読みしていましたが、私はこれらのコードを読んで私の髪を引き裂こうとしました。これらのコードはどのように正確に機能しますか?
ここで結び目に私の脳を得たコードです:
if (window === this) {
return new _(id);
}
_(ID)は、このコードが含まれているだけの関数名です。あなたがそれを見直す必要がある場合、残りのコードはここにあります。
function _(id) {
// About object is returned if there is no 'id' parameter
var about = {
Version: 0.5,
Author: "Michael Jasper",
Created: "Fall 2010",
Updated: "23 November 2011"
};
if (id) {
// Avoid clobbering the window scope:
// return a new _ object if we're in the wrong scope
if (window === this) {
return new _(id);
}
// We're in the correct object scope:
// Init our element object and return the object
this.e = document.getElementById(id);
return this;
} else {
// No 'id' parameter was given, return the 'about' object
return about;
}
};
以前は「新しい機能を返す」ことはありませんでしたが、その機能の仕組みを理解したいと思います。
コードの他の部分:
_.prototype = {
hide: function() {
this.e.style.display = 'none';
return this;
}
show: function() {
this.e.style.display = 'inherit';
return this;
}
};
私はこのコードは_オブジェクトに新しいメソッドを追加することを知っているが、なぜ彼らは「これを返す」のですか?私はそれを使わずに試してみました。
最後に一つ、記事へのリンクはhttp://www.mikedoesweb.com/2012/creating-your-own-javascript-library/
これが返されますか?だから、後に何かを追加することができますか?ちょうど推測 – Anonymous
'これを返す 'は' magic()。do()。stuff() 'のように連鎖を有効にします。 –
ええ、連鎖は私が言ったことです、それはjqueryのようですが、jqueryは少し複雑で多くのオブジェクトを返します。 – Anonymous