Question

What I want to do is to execute a function automatically every time BEFORE ANY function is executed in JS, regardless if it's a custom or native function if possible.

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

I do not want to do the following:

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

    blah.onBefore();

is it even possible to do what I am asking for? any suggestions, read, or w/e?

Thanks in advance.

Was it helpful?

Solution 2

what do you guys think about this solution? :)

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

OTHER TIPS

What about just providing your function as a callback to whatIWant like this:

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top