1

我想要做的是每次在 JS 中执行任何函数之前自动执行一个函数,如果可能的话,不管它是自定义函数还是本机函数。

IE。

    whatIWant(functionName){
      return console.log('called before '+functionName);
    } 

    function blah(){
      return console.log('called blah');
    }

    function meh(){
      return console.log('called meh');
    }

    alert('woot');


    blah();
    //will output :
    //called before blah
    //called blah

    meh();
    //will output :
    //called before meh
    //called meh

    alert();
    //will output :
    //called before alert
    //will pop up dialog: woot

我不想做以下事情:

    Function.prototype.onBefore = function(){};

    blah.onBefore();

甚至可以做我要求的吗?有什么建议、阅读或 w/e?

提前致谢。

4

2 回答 2

1

像这样将您的函数作为回调提供给 whatIWant 怎么样:

function whatIWant(fn) {
    var fnName = fn.toString();
    fnName = fnName.substr('function '.length);
    fnName = fnName.substr(0, fnName.indexOf('('));
    console.log('called before ' + fnName);
    fn();
}

function meh() {
    console.log('called meh');
}

function blah() {
    console.log('called blah');
}

whatIWant(meh);

whatIWant(blah);

whatIWant(alert)
于 2013-10-26T19:22:26.913 回答
1

你们怎么看这个解决方案?:)

  function bleh(){
    console.log('exe a');
  }

  function limitFn(fn,n) {
      var limit = n ;
      var counter = 1 ;
      var fnName = fn.toString();
      fnName = fnName.substr('function '.length);
      fnName = fnName.substr(0, fnName.indexOf('('));
      return function(){
        if(counter <= limit) {
          console.log(counter + ' call before ' + fnName + ' limit ' + limit);
          counter++;
          fn();
        } else {
          console.log('limit of ' + limit + ' exes reached') ;
        }
      };
  }



  limited = limitFn(bleh,2);

  limited();
  limited();
  limited();
  limited();
于 2013-10-26T20:03:59.373 回答