S
S
sasha2014-04-20 20:07:31
JavaScript
sasha, 2014-04-20 20:07:31

How to perform some action during any javascript function call?

So it became interesting, is it possible to call, say, console.log (1) with each call to any function?
I thought it would look something like this

Function.prototype.constructor = function (){
    Function.prototype.constructor();
    console.log(1);
};
function f() {
    console.log(2);
}
f()

but the output is only 2 :(

Answer the question

In order to leave comments, you need to log in

4 answer(s)
Y
Yuri Morozov, 2014-04-20
@madmages

As far as I remember, this is not possible.

D
Denis Pushkarev, 2014-04-20
@rock

No. Function.prototype.constructor is just a Function reference to identify the constructor instance. Here, the redefinition of the Function constructor will not help - functions are usually set by a literal, without using it. You can do this with those created through the constructor, but do you need it? :)

window.Function = (function(Function){
  return function(){
    var fn = Function.apply(window, arguments);
    return function(){
      console.log('run');
      return fn.apply(this, arguments);
    }
  }
})(Function);
Function('console.log(1)')() // => run 1

By the way, you have a Function.prototype.constructor call inside it - an endless recursive call. Yes, and console.log is also a function - if you do what you have formulated, you yourself will not be happy - also recursion.

M
Maxim Vasiliev, 2014-04-20
@qmax

It would be safer to replace all methods of the prototype/object of interest with wrappers.

S
Sergey Sova, 2015-12-21
@LestaD

Wait for the implementation of the objectProxy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question