誰もがJavaScriptで知っていますが、実際に遭遇するthis
例もあります。self
ここ
では、 JavaScript のthis
との違いは何でしょうか?self
ベストアンサー1
他に設定されていない場合、の値self
はwindow
JavaScriptx
の任意のプロパティに、 の代わりにwindow
として簡単にアクセスできます。したがって、は本当にx
window.x
self
window.self
、これはthis
。
window.self === window; // true
グローバルスコープで実行され、厳密モードではない関数を使用している場合、this
デフォルトで になりwindow
、したがって
function foo() {
console.log(
window.self === window, // is self window?
window.self === this, // is self this?
this === window // is this window?
);
}
foo(); // true true true
異なるコンテキストで関数を使用している場合、this
はそのコンテキストを参照しますが、self
のままですwindow
。
// invoke foo with context {}
foo.call({}); // true false false
定義window.self
はW3C 2006ワーキングドラフトウィンドウオブジェクト ここ。