実行コンテキスト | 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"ならば、グローバルオブジェクトを参照する。
モジュールコンテキストならば、トップレベルのthis
はundefined
になる。
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
で書かれているのがこの規則。