实施功能 - 间谍

时间:2014-11-18 10:16:35

标签: javascript function closures

目前我正致力于“间谍”其他功能。想法很简单:我只是用原始函数替换原始函数的调用加上计数器的递增。

问题是我的计数器只在内部范围内可见。如何将其公开给对象属性?

function Spy(target, method){
  this.count = 0;

  var counter = 0;

  target[method] = (function() {

    return function() {
      ++ counter;   
      this.count = counter;
      console.log(counter);
      return target[method];      
    };    
  })();
}

var spy = new Spy(console, 'error');

console.error('error1'); // prints 1, but not 'error1'
console.error('error2'); // prints 2, but not 'error2'
console.error('error3'); // prints 3, but not 'error3'

console.log(spy.count); // prints 0

3 个答案:

答案 0 :(得分:3)

我认为你正在寻找

function Spy(target, method){
  this.count = 0;

  var self = this,
      oldmethod = target[method];

  target[method] = function() {
    self.count++;
    console.log(self.count);
    return oldmethod.apply(target, arguments);      
  };
}

答案 1 :(得分:1)

试试这个:

function Spy(target, method){
  this.count = 0;

  var counter = 0;

  target[method] = (function(self) {

    return function() {
      ++ counter;   
      self.count = counter;
      console.log(counter);
      return target[method];      
    };    
  })(this);
}

答案 2 :(得分:1)

此代码可以使用:

function Spy(target, method){
  this.count = 0;

  var counter = 0;
  var self = this;

  target[method] = (function() {

    return function() {
      ++counter;   
      self.count = counter;
      console.log(counter);
      return target[method];      
    };    
  })();
}

您试图访问要返回的this内部函数范围