LoginSignup
0
0

More than 3 years have passed since last update.

javascriptのthisとbind、apply、callの使い方

Posted at

参考

thisの違いはこちらが分かりやすい。
JavaScriptの「this」は「4種類」??

bind()
Function.prototype.bind()

自分なりのまとめ

javascriptのfunction内のthisが示すものはは関数の呼び出し方によって異なる。
関数呼び出し時にthisを明示するために用いるのが下記の関数

  • call
  • apply
  • bind

call、apply

関数呼び出し時にthisを指定する。
callとapplyの違いは引数の取り扱いが違うくらい。

bind

関数のthisに予め任意のものを指定した関数を返す。
bindを使って受け取った関数はthisが固定されているためcallとapplyで呼び出し時に上書きすることは不可能。

確認

https://paiza.io/projects/ZJir-GpI4yZHafpMuZMmcQ?locale=en-us

process.stdin.resume();
process.stdin.setEncoding('utf8');
// Your code here!
value = 'global';

var myObject = {
  value: 'myObject',
  show: function() {
    console.log(this.value);
    return this.value;
  }
}
myObject.show(); // myObject

var show = myObject.show;
show(); // global
show.call(myObject); // myObject
show.apply(myObject); // myObject

show = myObject.show.bind(myObject);
show(); // myObject
show.call(global); //  myObject bindしたため無効
show.apply(global); // myObject bindしたため無効

show = myObject.show.bind(global);
show(); // global
show.call(myObject); // global bindしたため無効
show.apply(myObject); // global bindしたため無効
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