我如何使用 javascript 监听带有参数的特定函数调用:
示例:当调用 showname(2) 时,我也可以调用另一个函数,showage(2)
你可以把它包装起来:
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;
}
};
}();
您不能“挂钩”任意函数调用,不。
一种方法是向函数添加回调,例如定义:
function showname(firstname, lastname, callback){
alert(firstname + lastname);
if(callback) callback();
}
function showage(){
alert("who's age?");
}
并调用:
showname("John", "Doe", showage);