javascript - 为什么 `this`不指向window对象?

标签 javascript

在浏览器中,IIFE 内的 this 应该指向 window 对象。但是,在本例中它是未定义的。

(function () {

    "use strict";

    console.log(this) // undefined

    // more stuff

}());

最佳答案

在 ECMAScript 5 的严格模式中,,当 this 的值未定义或为 null 时(即不在对象范围内或 this 时)显式设置),this 不会从函数作用域返回全局对象。

调用函数时实际发生的情况如下 - ThisBinding 是调用时 this 值的行话 ( ECMA-262 )。

10.4.3 Entering Function Code

The following steps are performed when control enters the execution context for function code contained in function object F, a caller provided thisArg, and a caller provided argumentsList:

1. If the function code is strict code, set the ThisBinding to thisArg.
2. Else if thisArg is null or undefined, set the ThisBinding to the global object.

如果您想要全局对象,您可以使用在全局范围内定义的全局变量,或者使用一些解决此问题的技巧,例如使用立即调用的 new Function() 1.

1: 使用 new Function() 可以正常工作,因为它不会进入严格模式,除非该函数具有编译指示 'use strict';new Function() 本身的主体内 ( reference )。

关于javascript - 为什么 `this`不指向window对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400909/

相关文章:

javascript - ./src/index.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/

javascript - 如何在浏览器调试器工具中命名 eval 脚本文件?

javascript - 使 JavaScript 函数可行

javascript - 无法居中图像

javascript - 通过javascript获取特定的Windows版本

javascript - jQuery:从选择菜单的文本标签设置文本字段的值

javascript - 周围最近的坐标

javascript - 我不知道 Object(this) 是什么意思

javascript - 在关闭另一个 Bootstrap 模式后打开 Bootstrap 模式 - 意外行为

c# - 位置敏感的网站初始页面