#author("2022-07-26T03:25:10+09:00","","")
[[Javascript/デザインパターン]]

*Javascript/デザインパターン/Others/アロー関数(thisの扱い) [#d5052d79]

下記、コードでは、setTimeout では、this が Counter を指してほしいが、
全ての関数の外では、this は、グローバルオブジェクトを参照してしまうため、
一旦 self に this を入れて、setTimeout の中では self を利用している。
 let Counter = function() { this.count = 0; };
 Counter.prototype.inc = function() {
   const self = this;
   setTimeout(function() {
     self.count++;
     console.log(self.count);
   }, 1000);
 };
 
 let c = new Counter();
 c.inc();   // 1
 c.inc();   // 2

アロー関数内の this は、スコープ内のコンテキストの this を保持するので、
意図する書き方ができる(他言語と似たような意味合いのthisとなる)
 let Counter = function() { this.count = 0; };
 Counter.prototype.inc = function() {
   setTimeout(() => {
     this.count++;
     console.log(self.count);
   }, 1000);
 };
 
 let c = new Counter();
 c.inc();   // 1
 c.inc();   // 2


トップ   一覧 検索 最終更新   ヘルプ   最終更新のRSS