LoginSignup
0
0

More than 1 year has passed since last update.

bind call apply🍣

Posted at

参照先の結びつけができるbind,callそしてapplyの違いについてのめも

bindについて

→ b();

sushi.js
function x() {
    console.log('hello ' + this.name);
}

const tim = {name: 'Uni'};

const b = x.bind(uni); //xとtimの結びつけ
b();//bindメソッド使う場合、実行する記述が必要 b();


callとapplyの場合、thisとの結びつけから、実行まで一括で行われる

callの場合

sushi.js
//call 第二引数以下は、関数の引数を定義することができる。
function x(name) {
    console.log('hello ' + name);
}
const uni = {name: 'Uni'};

x.call(uni, 'Uni'); //結果 hello Uni         ここの'Uni'(関数の仮引数)を入れないと出力結果が'hello undefined'になる。

x.call(第一引数はthisの参照先のオブジェクト,第二引数以下が関数の引数として渡っていく)

applyの場合

sushi.js
//apply  第二引数に設定するのは配列 それがaに渡されて順番に展開される
function x(name,name1) {
    console.log('hello ' + name + ' ' + name1);
}
const uni = {name: 'Uni'};

x.apply(uni, ['Uni','Tuna']);

x.apply(第一引数はthisの参照先のオブジェクト,第二引数は配列)

→ 変数が独立している場合はcall、配列の場合はapplyを使う

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