在执行任何功能之前执行功能

时间:2013-10-26 18:39:07

标签: javascript function triggers onbeforeload

我想要做的是每次在JS中执行任何函数时自动执行函数,无论它是否是自定义函数或本机函数。

    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?

提前致谢。

2 个答案:

答案 0 :(得分:1)

如何将您的函数作为回调函数来提供这样的内容:

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)

答案 1 :(得分: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();