user6727528
user6727528

Reputation:

JavaScript run code before a function

How can I execute some javascript before running a function? I have tried doing something like this:

Function.prototype._call= Function.prototype.call;
Function.prototype.call = function(src) {
    console.log('A function was called name = ', src)
    Function.prototype._call(src);
}

But that only works when I use

myfunction.call()

And I want the code to work when I call any function normally eg:

myfunction()

Upvotes: 2

Views: 3627

Answers (2)

Ram
Ram

Reputation: 144739

There is no such API in JavaScript. The closest thing is ECMAScript 2015's Proxy objects that provides "Meta Programming" features. The apply trap handler is called for function invocations:

var proxy = new Proxy(function functionName() { /* ... */ }, {
  apply: function(target, thisArg, argumentsList) {
     console.log('%s was called', target.name);
     // you may want to use the `Function.prototype.apply` 
     // instead of the `()` operator
     target();
  }
});

proxy();

Upvotes: 3

Pop-A-Stash
Pop-A-Stash

Reputation: 6652

There's no such thing built-in JavaScript. That's just something you have to implement yourself:

function MyClass() {
  var self = this;
  this.beforeEach = function() {
    //runs before each method
  }

  this.myFunction = function() {
    self.beforeEach();
    //function code
  }

  this.myOtherFunction = function() {
    self.beforeEach();
    //function code
  }

}

Not elegant, but it works.

Upvotes: 0

Related Questions