アップデート
次のようなことができるようにしたい場合は、次のようなことを行うFresh.notify.showMessage()
必要があります。関数にプロパティを割り当てるだけですnotify
。
var Fresh = {notify:function(){return 'notify called';}};
Fresh.notify.showMessage = function () { return this() + ' and showMessage, too!';};
Fresh.notify();//notify called
Fresh.notify.showMessage();//notify called and showMessage, too!
これはここで関数オブジェクトを指し、そのように呼び出すことができます(this()
=== Fresh.notify();
)。それだけです。
このコードには多くの問題があります。まず第一に、クロージャを使おうとしているのは素晴らしいことです。しかし、私の言うことを気にしないのであれば、あなたはそれらを最大限に活用していません。例:notify
メソッドには、関数宣言とjQueryセレクターが含まれています。これは、メソッドが呼び出されるたびに、新しい関数オブジェクトが作成され、セレクターによってdomが何度も検索されることを意味します。クロージャスコープで参照されている関数とdom要素だけを保持することをお勧めします。
(function()
{
var body = $("body");
var notifyDiv = $("#notify-container div")[0];
var notifyDivEq0 = $("#notify-container div:eq(0)");
var show = function ()
{
body.animate({marginTop: "2.5em"}, "fast", "linear");
notifyDivEq0.fadeIn("slow");
};
var hide = function()
{//notifyDiv is not a jQ object, just pass it to jQ again:
$(notifyDiv).hide();
};
var timeout = 20000;
var Fresh = {
notify:function()
{
//this doesn't really make sense to me...
//notifyDiv.id.substr(7,1) == "1" && (show(),setTimeout(hide,timeout));
//I think this is what you want:
if (notifyDiv.id.charAt(6) === '1')
{
show();
setTimeout(hide,timeout);//pass function reference
//setTimeout(hide(),timeout); calls return value of hide, which is undefined here
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
この場合、提案を行うのは困難ですが、それ自体では、このコードはあまり意味がありません。コードが機能していることを確認できるように(またはコードが失敗することを確認できるように)フィドルを設定することをお勧めします:P)