JavaScript: Send function as a parameter to another function (callbacks) JavaScriptを:別の関数(コールバック)へのパラメータとして関数を送る
Posted on 29. 29日に掲載した。 Jul, 2009 by Dragos in Coding , JavaScript & Ajax 7月、2009 符号化 、 のJavaScript&Ajaxのでドラゴシュで
I'm sure you've seen a lot of code where functions are send as parameters, usually working as function callbacks eg:私はあなたのコードは関数のパラメータとして送信されている多くは、通常の関数コールバックの例として働いて見て確信している:
setTimeout(function () { alert('test'); },1000); setTimeout(関数()()('テスト'警告;)、1000);
But how does the function setTimeout execute the passed function as a parameter?しかし、どのように関数のsetTimeoutのパラメータとして渡された関数を実行するのですか? The answer is simple, but I need to provide you an example to understand it答えは簡単ですが、私はあなたを理解する例を提供する必要があります ![]()
Let's create a simple function, accepting two parameters: first a boolean value, the second – a function.の簡単な関数を作成し、2つのパラメータを受け付けてみましょう:最初のブール値、2番目-関数です。 Our function will analyze the boolean parameter and in case the value is true , the function passed as a parameter will be executed.当社の関数を、大文字と小文字の値は、関数のパラメータとして渡されますが実行されますが trueのブール値のパラメータを分析する。
function simpleFunc(bool,func) {関数simpleFunc(は、func)Boolを( if(bool) func();場合(ブール値)func()の; } )
As you notice, we add parentheses after the name of the second parameter, because we'll treat it as a function.お気付きのため、我々の関数として扱うよ、我々は2番目のパラメータの名前の後に、括弧を追加します。 And that's te whole secret.とのは、テ全体の秘密。
Now that is how we will use the simpleFunc function:今ではどのように我々はsimpleFunc関数を使用することです:
simpleFunc(false,function() { alert('Yupee!'); }; // this won't alert anything, because the boolean parameter is false simpleFunc(falseの場合、関数()(('Yupee警告!');)これは、ブール値のパラメータはfalse / /これは、何も警告されません //example two / /例2 simpleFunc(true,function() { alert('Yupee!'); }); // this will alert Yupee! simpleFunc(trueの場合、関数()(('Yupee警告!');)); / /このYupee警告を表示します!![]()
Wish you luck!希望する幸運を!
Related posts:関連記事:
- Javascript: How to validate email address with JavaScript? Javascriptを:どのようにJavaScriptを使って電子メールアドレスを検証する?
- JavaScript: How to get the index (position within a group) of an object with jQuery? JavaScriptを:どのようにjQueryを使ってオブジェクトの(位置は 、 グループ内)のインデックスを取得する?
- JavaScript: What if jQuery animation doesn't fire/start? JavaScriptを:どのような場合はjQueryのアニメーションは火災/起動するのですか?
- Coding: How to get code suggestions and function completion in Netbeans? 符号化:どのようにコードへの提案とNetbeansの関数の完了を取得する?
- Coding:How to fetch user profile data with SSI.php from a SMF forum database 符号化:どのようにSMFのフォーラムのデータベースからSSI.phpを持つユーザープロファイルデータをフェッチする












































