简体   繁体   中英

How to handle a function call in JavaScript without modifying the function

I'm trying to catch and handle a function call to make something when the function is being called, but I can't modify the function itself because I'm writing an UserJS so I would like to work with the function provided to me.

So all I need is to create a kind of "event handler" but for a function call.

Example:

TestSample.sync = function (arg1, arg2, arg3){
        //some function things
}

So I need a handler to let me do some stuff every time when the function is being called.

How to do it using JS?

I solved the problem by overwriting the function with binded context and adding my code into it (i think it`s not a good practice but it worked for my case)

var __fakeFunc = window.TestSample.sync.bind(window.TestSample); 

// Overwrite the original function, adding extra actions.
        TestSample.sync = function (arg1, arg2, arg3)  {
        // Add any code you need
        // Call the original function using it's temporary variable.
        __fakeFunc(arg1, arg2, arg3);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM