LoginSignup
0
0

More than 3 years have passed since last update.

thisとbind-apply-callの基本

Posted at

thisとbind-apply-callをよくわかっていなかったので
自分なりに解釈

this

const person = {
  name: '次郎',
  hello: function () {
    console.log(`こんにちは${this.name}`)
  }
}

person.hello()//こんにちは次郎

オブジェクトのメソッドとして呼んだ場合「this」はそのオブジェクトを指す。

上記のメソッドを定数にいれて関数として実行した場合

const ref = person.hello
ref()//こんにちは

この時、メソッド内の「this」はグローバルオブジェクト(window)を指すことになる。

bind

thisを束縛できる。

const ref = person.hello.bind(person)//ここでオブジェクトを指定
ref()//こんにちは次郎


function fn0() {
  console.log('こんにちは' + this.name)
}
const a1 = fn0.bind({ name: '太郎' })//オブジェクトをここで作っても渡せる
a1()//こんにちは太郎


function fn1(name) {
  console.log('こんにちは' + name + ' 年齢:' + this.age)
}
const b = fn1.bind({ age: 32 }, '次郎')//引数の束縛もできる
b()//こんにちは、次郎 年齢:32
b('三郎')//引数をいれてもbindが優先されるため、nameは次郎のままになる

bind」を使う事で「this」の参照先を固定できる
第一引数に「this」の参照先、第二引数から関数の引数
.bind(オブジェクト, 引数)

call&apply

基本はbindと同じだが呼んだ時点で実行される

function fn2(name, age) {
  console.log(`国>${this.country}_名前>${name}_年齢>${age}`)
}

const country = { country: '日本' }
fn2.apply(country, ['五郎', 19])//国>日本_名前>五郎_年齢>19
fn2.call(country, '八郎', 11)//国>日本_名前>八郎_年齢>11
fn2.bind(country, '六郎', 17)//この時点では実行されない

配列には「apply」、個別の引数には「call

以上!

間違いがあったらご指摘いただけるとうれしいです。

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