Last Updated: September 09, 2019
·
10.99K
· anasnakawa

Intercepting JavaScript methods

If for some reason you want to intercept any JavaScript method, so whenever this method is called, you want to inject a piece of code to be executed either before or after it..

for example the following code, will log to console each new item is pushed to any array in the system, also it will warn us if any array goes beyond the 1000 element...

// cache a  reference for original
// Array push method
var _push = Array.prototype.push;

// define your own push method
Array.prototype.push = function( item ) {

    // before Array push is called
    console.log( 'pushing ', item, ' into ', this );

    // call original Array push method
    _push.apply( this, arguments );

    // do whatever you like after
    // the push has been called
    if( this.length > 1000 ) {
        console.warn( 'potential memory leak going on here!!', this );
    }
}

6 Responses
Add your response

You shouldn't change the built-in objects :P
Have a look at http://underscorejs.org/#wrap and https://github.com/gameboxed/YouAreDaBomb

over 1 year ago ·

totally agree Victor, this was just an example, and i was trying to detect memory leakage in arrays, so it was temporary solution

but mainly the idea applies anywhere not only limited to built-in objects :)

over 1 year ago ·

Yes, I know you are not extending natives, I was just teasing you :p

Some people use this approach for AOP - see hexagonal.js

over 1 year ago ·

@viczam using _.wrap you will do the same as @anasnakawa wrote

over 1 year ago ·

@avenger7x I know - https://github.com/documentcloud/underscore/blob/master/underscore.js#L715
I just wanted to point out some libraries that does that for you. It's better to use named conventions when working in a team.

over 1 year ago ·

every time i see underscore.js used somewhere, it just gets more awesome.

over 1 year ago ·