Skip to content

Instantly share code, notes, and snippets.

@masudak
Last active August 29, 2015 14:12
Show Gist options
  • Save masudak/7c585aa0535bc125b887 to your computer and use it in GitHub Desktop.
Save masudak/7c585aa0535bc125b887 to your computer and use it in GitHub Desktop.
//-------------------------------------------
// sample1
// - callbackにするのは非同期のとき
// - 引数に渡すcallback関数を呼び出し元でいれかえることでhello関数自体が汎用的な処理になる
//-------------------------------------------
function hello_callback(){
console.log("called callback")
}
function hello(msg, callback) {
console.log("inside hello. msg: " + msg);
callback();
}
hello('hello', hello_callback) // hello_callback関数を引数として渡すことで内部で実行できるようになる
//-------------------------------------------
// sample2
// - hello_callback();以外の関数を実行することってできない
// - でも、hello2_callbackは実行できる気がする?
//-------------------------------------------
function hello22_callback() {
console.log("hello2_callback");
}
function hello2(msg) {
console.log("inside hello2. msg: " + msg);
hello_callback();
hello2_callback();
}
hello2('hello') //単にhello2のなかでグローバル関数のhello_callbackを呼ぶだけ。
//-------------------------------------------
// sample3
//-------------------------------------------
function hello3_callback2(){
console.log("called callback2");
}
function hello3_callback(callback){
console.log("called callback");
}
function hello3(msg, callback) {
console.log("inside hello. msg: " + msg);
callback();
}
hello3('hello', hello3_callback(hello3_callback2))
@masudak
Copy link
Author

masudak commented Dec 30, 2014

sample3はエラーになる。

実行結果:

called callback
inside hello. msg: hello

/home/share/masuda_kenichi/work/js/callback.js:73
    callback();

以下の部分で、引数内で関数を実行してしまっていているから?

hello3('hello', hello3_callback(hello3_callback2))

@masudak
Copy link
Author

masudak commented Dec 30, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment