[英]What causes "illegal invocation error" in this f.apply
'use strict';
function delay(f, ms) {
return function() {
setTimeout(() => f.apply(this, arguments), ms); //Illegal invocation
};
}
let obj = {length: 20};
obj.f1000 = delay(alert, 1000);
obj.f1000(this.length);
Why do I get illegal invocation error?为什么会出现非法调用错误? If the value of this is obj, then the function should just alert "20" without any problems?如果它的值为 obj,那么 function 应该只提示“20”没有任何问题?
Because you're calling alert
with a this
value it doesn't expect: your object. The reason that's happening is that you're calling the traditional function that delay
returns as a method ( obj.f1000
), which means during the call to the function this
refers to the object, and you're passing this
as the first argument to apply
in f.apply(this, arguments)
.因为您正在使用它不期望的this
值调用alert
:您的 object。发生这种情况的原因是您正在调用传统的 function delay
作为方法返回( obj.f1000
),这意味着在调用期间function this
指的是 object,您将this
作为第一个参数传递给apply
f.apply(this, arguments)
。 So alert
sees your object as this
.所以alert
将您的 object 视为this
。
To fix it, use null
or undefined
instead of this
with apply
:要修复它, this
使用null
或undefined
而不是apply
:
'use strict'; function delay(f, ms) { return function() { setTimeout(() => f.apply(null, arguments), ms); //Illegal invocation // −−−−−−−−−−−−−−−−−−−−−−−−−−^^^^ }; } let obj = {length: 20}; obj.f1000 = delay(alert, 1000); obj.f1000(this.length);
(You could also use window
if you wanted.) (如果需要,您也可以使用window
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.