[英]Illegal invocation on spy object
I am trying to create a Spy
object which will monitor how many times a method on another object gets called. 我正在尝试创建一个Spy
对象,该对象将监视在另一个对象上调用一个方法的次数。 I can get the monitoring working by wrapping the target's method in my Spy
, but when I try to invoke the target's method, I get an Illegal invocation
error, and I'm unsure why. 我可以通过将目标的方法包装在Spy
来使监视工作,但是当我尝试调用目标的方法时,出现了Illegal invocation
错误,我不确定为什么。
function Spy(target, method) {
var counter = 0;
var oldFunc = target[method];
target[method] = function(args){
return (function(){
counter++;
oldFunc(args); //ILLEGAL
})();
}
return { count : counter }
}
var spy = Spy(console, 'error');
console.error('foo', 'bar');
console.error('foobar');
console.log(spy.count);
Main problems with your function invocation are: 函数调用的主要问题是:
this
value 您没有通过预期的this
值 Use the apply
method to fix this. 使用apply
方法解决此问题。 Btw, that IEFE is useless, and you're not updating the .count
property, but only the local counter
variable. 顺便说一句,IEFE是没有用的,您不是在更新.count
属性,而是在更新本地counter
变量。
function Spy(target, method) {
var counter = 0;
var oldFunc = target[method];
target[method] = function() {
counter++;
return oldFunc.apply(this, arguments);
};
return { get count() { return counter; } }
}
( updated demo ) ( 更新的演示 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.