0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】【Vue】 など流行りのフレームワークを使うもののためのJS基礎 [this, call(), apply(), bind()]

Last updated at Posted at 2022-01-13

this

thisは、その関数を呼び出しているオブジェクト グローバルスコープで呼び出した場合は、グローバルオブジェクト javaScriptは一番外におおきなグローバルオブジェクトで囲まれているため。

bind()

thisが参照するオブジェクトを指定する


const myButton = {
    content: 'OK',
    click() {
      console.log(this)
      console.log(this.content + ' clicked');
    }
  };

myButton.click();

//コンソール
{ content: 'OK', click: [Function: click] }
OK clicked

この場合の this は myButton のオブジェクトを示している

では次の場合はどうなるだろうか

myButton クラスのメソッドを変数 looseClick に代入している


const myButton = {
    content: 'OK',
    click() {
      console.log(this)
      console.log(this.content + ' clicked');
    }
  };

const looseClick = myButton.click;
looseClick();

//コンソール
Object [global]
undefine clicked

この場合の this はグローバルオブジェクトを示している

なぜかというと looseClick には

    click() {
      console.log(this)
      console.log(this.content + ' clicked');
    }

が代入されている

記事の最上部に書いたが、この時の this は myButton のようなクラスに囲まれていない
→ グローバルオブジェクトを示している

これを※と同じ動きにするには bind を使用する


const myButton = {
    content: 'OK',
    click() {
      console.log(this)
      console.log(this.content + ' clicked');
    }
  };

const bindClick = myButton.click.bind(myButton);
bindClick();

//コンソール
Object [global]
undefine clicked

click メソッドの中にある this が myButton オブジェクトを指していることを bind をつかって指定する

追記予定
call
applay

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?