为什么我们不能在 setTimeout 上调用和应用?

why can't we do call and apply on setTimeout?

为什么我们不能在 setTimeout 上调用和应用,

var obj={}
window.setTimeout.call(obj,callback,delay);//it throws error stating illegal invocation 

来自WHATWG setTimeout documentation

The setTimeout() method must return the value returned by the timer initialisation steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to false.

setTimeout 需要从 window 对象的上下文中调用。传递给 .call 方法的上下文不是 window 对象。要正确调用 setTimeout,请执行:

setTimeout.call(window, callback, delay);

setTimeout 上使用 .call 没有任何意义,因为 .call 旨在调用函数并在调用时为该函数提供上下文。换句话说,您不是在尝试调用 setTimeout 并提供上下文,而是在尝试调用 回调 提供上下文。

要使用 setTimeout 完成此操作,您需要使用 .bind,如:

 var obj={};
 window.setTimeout(callback.bind(obj),delay);