ホームページ  >  記事  >  ウェブフロントエンド  >  JavaScriptで関数の実行回数をカウントするにはどうすればよいですか? (詳しい説明)

JavaScriptで関数の実行回数をカウントするにはどうすればよいですか? (詳しい説明)

不言
不言転載
2018-10-27 14:14:184500ブラウズ

この記事の内容は、JavaScriptで関数の実行回数をカウントする方法についてです。 (詳細な説明)は、必要な友人が参考にできることを願っています。

1. 関数の実行数をカウントする

従来の方法では、console.log の出力を使用して、肉眼で出力の数を計算することができます

しかし、Chrome には、文字列が出力された回数をカウントできる組み込みの console.count メソッドがあります。これを使用して、関数の実行回数を間接的にカウントすることができます

function someFunction() {
 console.count('some 已经执行');
}
function otherFunction() {
 console.count('other 已经执行');
}
someFunction(); // some 已经执行: 1
someFunction(); // some 已经执行: 2
otherFunction(); // other 已经执行: 1
console.count(); // default: 1
console.count(); // default: 2

パラメータを指定しないと、これがデフォルト値になります。それ以外の場合は、文字列の実行回数が出力されるため、観察するのに非常に便利です

もちろん、回数を出力するだけでなく、純粋な回数も取得したい場合は、関数をデコレータでラップし、オブジェクトを使用して呼び出し回数を内部的に保存することができます

var getFunCallTimes = (function() {
 
 // 装饰器,在当前函数执行前先执行另一个函数
 function decoratorBefore(fn, beforeFn) {
 return function() {
 var ret = beforeFn.apply(this, arguments);
 // 在前一个函数中判断,不需要执行当前函数
 if (ret !== false) {
 fn.apply(this, arguments);
 }
 };
 }
 
 // 执行次数
 var funTimes = {};
 
 // 给fun添加装饰器,fun执行前将进行计数累加
 return function(fun, funName) {
 // 存储的key值
 funName = funName || fun;
 
 // 不重复绑定,有则返回
 if (funTimes[funName]) {
 return funTimes[funName];
 }
 
 // 绑定
 funTimes[funName] = decoratorBefore(fun, function() {
 // 计数累加
 funTimes[funName].callTimes++;
 console.log('count', funTimes[funName].callTimes);
 });
 
 // 定义函数的值为计数值(初始化)
 funTimes[funName].callTimes = 0;
 return funTimes[funName];
 }
})();

function someFunction() {
 
}
function otherFunction() {
 
}
someFunction = getFunCallTimes(someFunction, 'someFunction');
someFunction(); // count 1
someFunction(); // count 2
someFunction(); // count 3
someFunction(); // count 4
console.log(someFunction.callTimes); // 4
otherFunction = getFunCallTimes(otherFunction);
otherFunction(); // count 1
console.log(otherFunction.callTimes); // 1
otherFunction(); // count 2
console.log(otherFunction.callTimes); // 2

関数呼び出しの数を制御する方法

クロージャを使用して関数の実行数を制御することもできます

function someFunction() {
 console.log(1);
}
function otherFunction() {
 console.log(2);
}
function setFunCallMaxTimes(fun, times, nextFun) {
 return function() {
 if (times-- > 0) {
 // 执行函数
 return fun.apply(this, arguments);
 } else if (nextFun && typeof nextFun === 'function') {
 // 执行下一个函数
 return nextFun.apply(this, arguments);
 }
 };
}
var fun = setFunCallMaxTimes(someFunction, 3, otherFunction);
fun(); // 1
fun(); // 1
fun(); // 1
fun(); // 2
fun(); // 2

以上がJavaScriptで関数の実行回数をカウントするにはどうすればよいですか? (詳しい説明)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はsegmentfault.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。