你能否告诉我如何编写一个函数来检查一个特定的函数是否被调用,调用了多少次 - 有或没有参数。
提前感谢你
答案 0 :(得分:1)
@ elclanrs的解决方案非常好,但它存在多个问题:
您需要调用跟踪器功能而不是原始功能。这意味着您需要更改一些原始代码才能使用它。
您需要存储对跟踪器对象的引用才能获得计数。
以下是解决这些问题的方法:
function track() {
var calls = [],
context = window,
funcName,
i = 0;
if (arguments.length === 1) {
context = window;
funcName = arguments[0];
} else {
context = arguments[0];
funcName = arguments[1];
}
var func = context[funcName];
context[funcName] = function () {
calls.push({
count: i++,
args: Array.prototype.slice.call(arguments)
});
return func.apply(context, arguments);
};
context[funcName].getCalls = function () {
return calls;
};
}
用法示例:
// The function we want to track.
function log(val) {
console.log(val);
}
// Start tracking the function
track('log');
// Normal usage of the function
log('Message 1');
log('Message 2');
// Print the collected data of the function
console.log(log.getCalls());
/*^
[ { count: 0, args: [ 'Message 1' ] },
{ count: 1, args: [ 'Message 2' ] } ]
*/
注意:如果您的函数不在全局上下文中(例如:document.getElementById
),则需要执行以下操作:
track(document, 'getElementById');
然后您可以正常收集数据:
document.getElementById.getCalls()
答案 1 :(得分:0)
你可以创建一个函数装饰器来保存闭包中的计数和参数,例如:
// Helper to convert pseudo-arrays
// such as `arguments` to real arrays
var __slice = Array.prototype.slice;
// Higher-order function that
// returns a function that saves the count
// and arguments when called
function track(f) {
var i = 0; // count
var calls = []; // array to save the info
var fn = function() {
// Save arguments and incremented counter
calls.push({
count: i++,
args: __slice.call(arguments)
});
// Call the original function with arguments
// preserving the context, and return its value
return f.apply(this, arguments);
};
// A function, attached to the decorated function,
// that gets the info out of the closure
fn.count = function() {
return calls;
};
// Return decorated function to be used
return fn;
}
// Decorate a normal function
var add1 = track(function(x) {
return x + 1;
});
// Run the function 3 times
// Internally the decorated function will keep
// track of the count and arguments
add1(1);
add1(2);
add1(3);
// Using the `count` function of our decorated function
console.log(add1.count());
/*^
[ { count: 0, args: [ 1 ] },
{ count: 1, args: [ 2 ] },
{ count: 2, args: [ 3 ] } ]
*/
答案 2 :(得分:0)
每个函数都定义了一个调用者属性。你可以这样做
function callfn() {
if (callfn.caller == null) {
return ("The function was called from the top!");
} else
return ("This function's caller was " + callfn.caller);
}
}
答案 3 :(得分:0)
尝试这样的事情
var counter = {};
counter.with_param = 0;
counter.without_param = 0;
function test(arg){
if(!arg){
counter.without_param = counter.without_param + 1;
}else{
counter.with_param = counter.with_param + 1;
}
}
test(1);
test(5);
test();
test();
test(6);
console.log('WITH PARAM ' + counter.with_param);//3
console.log('WITHOUT PARAM ' + counter.without_param);//2
console.log('TOTAL CALLING ' + (counter.with_param + counter.without_param));//5