通常の JSを理解しようとしているので、名前付きコールバックを使用するのが最も興味深いアプローチだと思います。
$(document).ready(function()
{
function animateCube(e)//can be declared outside ready CB, too
{//jQuery passes the event object to the function
$(this).fadeOut();//? fade only clicked element?
$('.test').fadeOut();
$('.test').delay(500).slideDown();
}
$('.link, .test').on('click',animateCube);
});
知っておく必要があるのは、関数はファースト クラスのオブジェクトであり、jQuery で常に行うように、別の関数に引数として渡すことができるということです ( .click(function
<---)。.click(function() { anotherFunction();});
そのため、私見を書くのは本当に意味がありません。その場で二次関数オブジェクトを作成し、それが呼び出された場所でそれを jQuery に渡します。実行されるのを確認したい関数を呼び出すだけです。実際、関数は特定のコンテキスト ( $(this)
) で呼び出されます。これは、使用したいコンテキストです。ダミー関数をラップしても意味がありません。特定の関数に追加のものを追加したい場合は、それらをオブジェクトとして扱います. それらは引数、関数の戻り値、プロパティを持つことができ、プロトタイプ(-chain)を与え、一度に複数の変数によって参照することさえできます...これを考慮してください:
$(document).ready(//<-- open bracket: this is a function call
function(){});//we're creating a function AND pass it as an argument
したがって、ready
呼び出したメソッドは次のようになります (これよりも少し複雑に見えますが、それは重要ではありません)。
object.ready = function(functionArgument)
{
//the function we passed looks like a variable now:
console.log(typeof functionArgument);//"function"
//ways this function can be called:
functionArgument();
functionArgument.call(this);//call in current context
functionArgument.apply(object,[1,2,3]);//call as a method of object, and pass 3 arguments
functionArgument.bind(window);//bind global context
functionArgument();//call in bound context
};
関数は JS の優れたものであり、繰り返しになりますが、関数もオブジェクトであるため、他のオブジェクトと同様にプロパティを割り当てることができます。この例では:
functionArgument.hasAProperty = functionArgument;
functionArgument = (function(originalFunction)//this was the original function
{
return function()//<-- return a function, that will be assigned to our var
{
console.log('I used to be:');
console.log(oringalFunction);
console.log('Now I do even more! But did I loose my property?');
console.log(typeof functionArgument.hasAproperty);//undefined
console.log('Yes, but: ' + typeof originalFunction.hasAProperty + ' Not entirely!');
};
})(functionArgument.hasAProperty);//passes a reference to itself
これがあなたにとって意味があるかどうか教えてください。これはテストされていませんが、IIFE とクロージャーの基本原則に従っています。