我可以使用javascript听一个函数调用吗?

Moh*_*ued 7 html javascript web

如何使用javascript听参数的特定函数调用:

例如:当showame(2)被调用时,我可以做类似于调用另一个函数的东西,showage(2)

bev*_*qua 15

你可以包装它:

var native = window.alert;

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

alert('test');
Run Code Online (Sandbox Code Playgroud)

更新

您可以使用getter和/或setter来执行与属性类似的操作:

var foo = {
     bar = 'baz'
};
Run Code Online (Sandbox Code Playgroud)

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';
Run Code Online (Sandbox Code Playgroud)

封装(私有_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;
        }
    };
}();
Run Code Online (Sandbox Code Playgroud)