LoginSignup
0
1

More than 3 years have passed since last update.

【JavaScript】this

Posted at

下記のようなクラスがあるとします。

class Person {
    constructor(name,age) {
      this.name = name
      this.age = age
    }
    hello() {
      console.log(`my name is = ${this.name}. ${this.age} years old.`)
    }

関数内でthisを呼び出す場合、下記のような書き方だとTypeError: this.hello is not a functionとなりエラーになります。

    remember(){
      setTimeout(function() { 
          this.hello(); 
      }, 1000);
    }

JavaScriptでは、関数内のthisは関数自体を指すため、hello()なんてないですよと怒られている状態です。
そのため、一度別の定数に退避させる必要があります。

    remember(){
      const self = this 
      setTimeout(function() { 
          self.hello(); 
      }, 1000);
    }

一度退避することで、呼びたいthisを正しく呼び出すことができます。

thisを退避させずに呼び出すには、bindメソッドを使います。

    remember2(){
      // self = thisが不要
      setTimeout(function() { 
          this.hello(); 
      }.bind(this), 1000);
    }

bindは束縛という意味です。

また、アロー関数にしてしまうとさらに短縮できます。

remember3() {
    // self=thisが不要
    setTimeout(()=>{ 
      this.hello();
    }, 1000);
  }
0
1
2

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
1