为什么'this'的值会因文档而异

shr*_*e33 5 javascript jquery this

在下面的代码我无法理解为什么值this更改为window从document在功能上handler,当我把它从document上下文.

$(document).ready(function() {

  var handler = function() {
    console.log(this);       // this = window
  }
  console.log(this);    // this = document
  handler();
})
Run Code Online (Sandbox Code Playgroud)

根据我的理解,价值this取决于其执行背景.现在当我是预期的document.ready功能this点document时,但是当我从该上下文调用方法时,为什么我的上下文会window从中变为document.

提前致谢.

Nik*_*eja 4

在函数内部, 的值this取决于函数的调用方式。

var handler = function () {
    console.log(this); // this = window
};
Run Code Online (Sandbox Code Playgroud)

在这种情况下, 的值this不是由调用设置的。由于代码不是严格模式,所以 this 的值必须始终是一个对象,因此它默认为全局对象,即 window。

在全局执行上下文中(在任何函数之外),this引用全局对象,无论是否处于严格模式。

console.log(this); // this = document
Run Code Online (Sandbox Code Playgroud)