Can calls to a module or class be intercepted in node.js/Javascript

979 Views Asked by At

In PHP every class contains a "magic" __call function. Using this one can dynamically intercept all calls to a class. For example using

class TestClass {

    public function __call($functionname, $arguments) {

        .. functionname called 

    }

}

See http://www.php.net/manual/en/language.oop5.overloading.php#object.call

Is something similar possible in JavaScript/Node.js? Either on a module (loaded by require) or for classes?

Update: Thank you for all who commented. This does not seem to be possible in pure JavaScript. At least currently.

1

There are 1 best solutions below

1
On

You could do something like this, though it's per-function:

// original module
var module = {
   myFunc: function(){ /* ... */ }
}

// "spying" code

var originalFunction = module.myFunc;

module.myFunc = function(){
    // DO SPY STUFF HERE

    return originalFunction.apply(this, arguments);
};

http://jsfiddle.net/9eu45/