1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[JavaScript] Arrow Function Test

1
Last updated at Posted at 2015-12-11
JavaScript
window.status = "window";

// callback: normal function
var obj1 = {
  status: "obj1",
  func: function() {
    // this=window
    setTimeout(function(){alert(this.status);}, 1000);
  }
};
obj1.func(); // ⇒ "window"

// callback: arrow function
var obj2 = {
  status: "obj2",
  func: function() {
    // this=obj2
    setTimeout(()=>{alert(this.status);}, 1000);
  }
};
obj2.func(); // ⇒ "obj2"

アロー関数の特長:
obj > function > arrow function
という位置関係の時、arrow function 内の this は必ず obj を指します。つまり静的に決定されます。
コールバックが通常の function においては、this はコールバックを実行した主体(オブジェクト)を指します。つまり、動的に決定されますので、注意が必要です。

ソースデモはこちら

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?