我如何使用javascript监听带参数的特定函数调用:示例:当调用show name(2)时,我可以执行类似调用另一个函数的事情,showage(2)
答案 0 :(得分:14)
你可以包装它:
var native = window.alert;
window.alert = function(){
console.log('alerting...');
native.apply(window, arguments);
console.log('alerted!');
};
alert('test');
您可以使用getter和/或setter来执行与属性类似的操作:
var foo = {
bar = 'baz'
};
到
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';
封装(私人_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 :(得分:0)
一种方法是向函数添加回调,例如define:
function showname(firstname, lastname, callback){
alert(firstname + lastname);
if(callback) callback();
}
function showage(){
alert("who's age?");
}
并致电:
showname("John", "Doe", showage);
答案 2 :(得分:0)
你不能“挂钩”任意函数调用,没有。