LoginSignup
1
0

More than 1 year has passed since last update.

JavaScriptのthisとbindについて

Last updated at Posted at 2021-06-05

はじめに

jsの勉強をしているので備忘録として残しておきます。
間違っていたらすみません...

jsのthisとは?

JavaScriptのthisとはオブジェクトを参照するキーワードのこと

const obj = {
  first_name: '山田',
  last_name: '太郎',
  putFullname: function() {
        //thisを用いる場合
    console.log(this.last_name);

        //thisを用いない場合
        console.log(obj.last_name);
  }
}

//両方とも出力結果は太郎になる
obj.putFullname();

オブジェクト内にthisを用いる時、上のコードの場合だとthisはオブジェクトであるobjを指している。

thisをクラス内で用いる場合

クラスを作成しただけではオブジェクトは生成されていないので、下記の場合のthisは何も参照していない。

class Obj {
  constructor() {
    this.first_name = '山田';
    this.last_name = '太郎';
  }

  putFullname() {
    console.log('hello');
  }
}

なのでクラス外でオブジェクトを生成することで初めて、thisがオブジェクトを参照することができる。

class Obj {
  constructor() {
    this.first_name = '山田';
    this.last_name = '太郎';
  }

  putFullname() {
    console.log(this.last_name);
  }
}

//ここでオブジェクトを生成。この場合thisが参照するオブジェクトはobj2となる。
const obj2 = new Obj();

//出力結果は太郎になる
obj2.putFullname();

オブジェクトが階層になっている場合

オブジェクトが階層になっている場合、thisは階層を上がって行った時に最初に見つかるオブジェクトを参照する。

const obj = {
  first_name: '山田',
  last_name: '太郎',
  putFullname: function() {
        //この場合のthisはobjを参照する
    console.log(this.last_name);

        window.setTimeout(function() {
        //この場合のthisはwindowを参照する
        console.log(this);
    })
  }
}


obj.putFullname();

bindについて

下記のwindowオブジェクトの中でwindowではなく、objを参照したい場合はどうすれば良いのか?
そんな時に用いるのがbindである。
bindの第一引数に与えられたものをオブジェクトとすることができる。

const obj = {
  first_name: '山田',
  last_name: '太郎',
  putFullname: function() {
        //この場合のthisはobjを参照する
    console.log(this);

        window.setTimeout(function() {
        //この場合のthisはobjを参照する
        console.log(this);
    }.bind(this));
    //bindの第一引数のthisがobjを参照しているので、上記のwindowオブジェクト内のthisもobjを参照している。
  }
}


obj.putFullname();
//出力結果は下記がコンソールに2つ出力される
{first_name: "kkk", last_name: "太郎", setFullname: ƒ}
first_name: "kkk"
last_name: "太郎"
setFullname: ƒ ()
__proto__: Object

まだまだ勉強中なので編集すると思います。

1
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
1
0