0
0

More than 1 year has passed since last update.

JavaScriptのsetTimeout(func.bind(null,value));のbind周りを書く意味

Posted at

詰まったので自分用メモ

結論

  • setTimeoutの第一引数は関数じゃないと効かないっぽい
  • bindの返り値は新しい関数
    func.bindで新しい関数を作り、それをsetTimeoutに渡してるから動くっぽい

例)
hello.bind(null,cat)が実行されてからsetTimeoutに渡されている
hello.bind(null,cat)の返り値はhello(cat){console.log('こんにちは!! ' + cat);}というhelloメソッドの引数だけcatになったやつ
=>setTimeout(hello(cat),1000);になって1秒後に出力される

function hello(animal){
    console.log('こんにちは!! ' + animal);
}

const cat="ネコチャン";
setTimeout(hello.bind(null,cat),1000); // 1s後に「こんにちは!! ネコチャン」

↓setTimeoutが効かないやつ

  • hello(cat)が実行され(この時点で出力されてる)てからsetTimeoutに渡されている
    =>helloメソッド自体に返り値がないからsetTimeout(undefined,1000);
function hello(animal){
    console.log('こんにちは!! ' + animal);
}

const cat="ネコチャン";
setTimeout(hello(cat),1000); // 即「こんにちは!! ネコチャン」

bind(null,value)の意味

  • bindは引数とthisの束縛ができるよ
    • thisの場合、第一引数にオブジェクトを指定する
    • 引数の場合、第一引数にnullを指定
function hello(animal){
    console.log('こんにちは!! ' + animal);
}

const animals= {
    cat : "ネコチャン"
}
setTimeout(hello.bind(animals,cat),1000); // 1s後に「こんにちは!! ネコチャン」

bind以外でも書けるみたいだよ

  • setTimeoutの第一引数が関数として渡せればいいから他の書き方でもいける
// 例1
function hello(animal){
   return function(){ 
       console.log('こんにちは!! ' + animal);
   }
}
const cat="ネコチャン";
setTimeout(hello(cat),1000);
// 例2
function hello(animal){
       console.log('こんにちは!! ' + animal);
}
const cat="ネコチャン";
setTimeout(function(){hello(cat)},1000);

参考にしたもの

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0