简体   繁体   English

对间谍对象的非法调用

[英]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);

http://jsfiddle.net/s505eemb/ http://jsfiddle.net/s505eemb/

Main problems with your function invocation are: 函数调用的主要问题是:

  • you're not passing all arguments 你没有通过所有论点
  • you're not passing the expected this value 您没有通过预期的this
  • you're not returning the result value 您没有返回结果值

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM