12

How can i listen to a specific function call with parametters using javascript:

example : when showname(2) is called i can do something like call another function too, showage(2)

3
  • 3
    Just modify the function.
    – SLaks
    Commented Feb 7, 2013 at 19:37
  • 1
    use a callback maybe ? Commented Feb 7, 2013 at 19:39
  • add function call statement inside the function
    – Lupus
    Commented Feb 7, 2013 at 19:40

3 Answers 3

20

you can wrap it:

var native = window.alert;

window.alert = function(){
    console.log('alerting...');
    native.apply(window, arguments);
    console.log('alerted!');
};

alert('test');

update

you can do something similar with properties, using getters and/or setters:

var foo = {
     bar = 'baz'
};

into

var foo = {
    _bar: 'baz',
    get bar(){
        console.log('someone is taking my bar!');
        return this._bar;
    },
    set bar(val){
        console.log('someone pretends to set my bar to "' + val + '"!');
        this._bar = val;
    }
};

alert(foo.bar);

foo.bar = 'taz';

encapsulated (private _bar):

var foo = function(){
    var _bar = 'baz';

    return {
        get bar(){
            console.log('someone is taking my bar!');
            return _bar;
        },
        set bar(val){
            console.log('someone pretends to set my bar to "' + val + '"!');
            _bar = val;
        }
    };
}();
1
  • Now I remember wrapping console.error to fetch console errors for logging...I also have a unit test for that :D
    – Guntram
    Commented Jan 5, 2021 at 13:14
0

You can't "hook" into arbitrary function calls, no.

1
  • 1
    You can by wrapping the original function, as @bevacqua supposes.
    – Guntram
    Commented Jan 5, 2021 at 13:10
-2

One way to do it is to add a callback to the function, for example define:

function showname(firstname, lastname, callback){
    alert(firstname + lastname);
    if(callback) callback();
}

function showage(){ 
   alert("who's age?");
}

And call:

showname("John", "Doe", showage);
1
  • imo, a callback is not an answer to the question "can i listen to a function call using javascript?"
    – Guntram
    Commented Jan 5, 2021 at 13:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.