Is it possible to override the “call” function on a generic level, so that every time when a method gets called anywhere in the app, something happens.
I tried overriding Object.call, but although I managed to do it, it didn’t change anything in the way my app works.
BTW, even if it works, should I explicitly call “foo.call(this,args)” every time, or normal function calls will also work “foo(args)” ?
Sounds like you want to do some kind of aspect oriented programming here….
JavaScript, as an ECMAScript dialect, does have the notion of a callable object. Every callable object has an internal property called
[[Call]]. This property is described in Section 8.6.2, Table 9, of the ECMA-262 Specification, 5th edition. It says:But the thing to be aware of is that
[[Call]]is an internal property, for which the spec says:So you can not hook into this mechanism in your own JavaScript code.
Now there are two methods defined in
Function.prototype,applyandcall. It is true that if you change the definition ofFunction.prototype.callthen if you create your own functionf, thenf.callwill indeed (unless overridden in f’s prototype or in f itself) execute that code. This will, as you presumed, NOT automatically happen by callingfdirectly. You have to explicitly call thecallmethod.All that said, it is best not to muck with predefined, standard methods in the prototypes of built-in objects. A lot of existing code in libraries and applications depend on
Function.prototype.call. Don’t mess with it. You can, of course, implement a kind of AOP behavior in many ways. One is to add toFunction.prototypesome other method, but don’t do this either. Another is to write your own call method with before and after hooks: