在浏览器中,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/