Skip to content

Instantly share code, notes, and snippets.

@azu
Created January 4, 2018 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azu/9833e2f66bc8f0c97258ab0c81258469 to your computer and use it in GitHub Desktop.
Save azu/9833e2f66bc8f0c97258ab0c81258469 to your computer and use it in GitHub Desktop.
実行コンテキスト strict mode コード thisの評価結果
Script NO this global
Script NO const fn = () => this global
Script NO const fn = function(){ return this; } global
Script YES this global
Script YES const fn = () => this global
Script YES const fn = function(){ return this; } undefined
Module YES this undefined
Module YES const fn = () => this undefined
Module YES const fn = function(){ return this; } undefined
const obj = { method(){ return this; } } obj
const obj = { method: function(){ return this; } } obj
Script const obj = { method: () => { return this; } } global
Module const obj = { method: () => { return this; } } undefined
  • はどの場合でも結果に影響しないということを示す
  • 関数はfn()と実行した場合のthisの評価結果、メソッドはobj.method()と実行した場合のthisの評価結果。
const obj = { method: () => { return this; } }

は実質的に次と同じ。

console.log(this);

グローバルスコープにおけるthisは"Script"ならば、グローバルオブジェクトを参照する。 モジュールコンテキストならば、トップレベルのthisundefinedになる。

Relation with strict mode Given that this comes from the surrounding lexical context, strict mode rules with regard to this are ignored. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Relation_with_strict_mode

で書かれているのがこの規則。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment