前に「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;
}
};
「return new function」はこれまで見たことがありませんが、それがどのように機能するかを理解したいと思っています。
他のコード:
_.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/です。