【问题标题】:Implementing function - spy实现功能 - 间谍
【发布时间】:2014-11-18 10:16:35
【问题描述】:

目前我正在为其他功能开发“间谍”。想法很简单:我只是用原始函数加上计数器的增量替换原始函数的调用。

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

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

【问题讨论】:

    标签: javascript function closures


    【解决方案1】:

    我想你正在寻找

    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);      
      };
    }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      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);
      }
      

      【讨论】:

        【解决方案3】:

        此代码将起作用:

        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 范围

        【讨论】:

          猜你喜欢
          • 2018-12-26
          • 2020-10-26
          • 1970-01-01
          • 1970-01-01
          • 2020-07-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多