gpt4 book ai didi

javascript - 传递给 setTimeout 的函数 fn 是否不是作为函数调用,而是作为类似 window.fn() 的方法调用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:58:33 24 4
gpt4 key购买 nike

在严格模式下,this 在非方法(函数)内应该是undefined:

参见 http://jsfiddle.net/jfp06nc9/1/
显示 thisundefined

但是,当使用 setTimeout 时,this 将绑定(bind)到 window:

参见 http://jsfiddle.net/jfp06nc9/2/
http://jsfiddle.net/jfp06nc9/3/
显示 this === window 返回 true。

所以看起来传递给 setTimeout 的函数 fn 不是作为函数调用的,而是作为方法调用的,例如 window.fn()fn.call(window)(fn.bind(window))()

参见 http://jsfiddle.net/jfp06nc9/4/
显示上面的最后 3 个调用会将 this === window 全部显示为 true

这是真的吗?我找不到任何关于它的规范,所以请将其包含在您的回答中。

(jsfiddle 在 Chrome 46.0 中运行)

附言这个问题不是关于 this 绑定(bind)到什么,而是关于在非严格模式下,setTimeout 可以运行 fn()this 将绑定(bind)到 window。但是在严格模式下,如果 setTimeout 真的以 fn() 运行它,那么 this 现在应该是 undefined window,所以那里有一个细微的区别,似乎 setTimeout 运行它(或安排运行它)而不是 fn()但作为 fn.call(window)

jsfiddle 和代码:

http://jsfiddle.net/jfp06nc9/7/

(function() {
"use strict";
setTimeout(function() {
"use strict";
console.log(this);
}, 1000);
}());

由于函数运行在严格模式下,如果作为函数运行,那么this应该是undefined但实际上是window

最佳答案

setTimeout 是 HTML 规范的一部分(与 ECMAScript 相对),它确实阐明了 window 应该用于 this .

relevant part of the spec如下:

  1. Let method context proxy be method context if that is a WorkerGlobalScope object, or else the WindowProxy that corresponds to method context.

(强调我的)

连同:

4.2 Run the appropriate set of steps from the following list:

If the first method argument is a Function

Call the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function. Use method context proxy as the thisArg for invoking the Function.

(强调我的)

关于javascript - 传递给 setTimeout 的函数 fn 是否不是作为函数调用,而是作为类似 window.fn() 的方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33831452/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com