好的,這裏是我想到的方法,根本不需要修改函數。
所以,如果你有這個。
function someFunction() {
doingThings();
}
你可以添加這樣的反...
addCounter(this, "someFunction");
哪裏,這是你在範圍內,可以使用具有要算一個方法的對象。
下面是它的代碼。
<html>
<head>
<script>
function someFunc() {
console.log("I've been called!");
};
// pass an object, this or window and a function name
function wrapFunction(parent, functionName) {
var count = 0, orig = parent[functionName];
parent[functionName] = function() {
count++;
return orig.call(this, Array.prototype.slice(arguments));
}
parent[functionName].getCount = function() {
return count;
};
}
var someObj = {
someFunc: function() {
console.log("this is someObj.someFunc()");
}
}
wrapFunction(this, "someFunc");
wrapFunction(someObj, "someFunc");
someFunc();
someObj.someFunc();
someObj.someFunc();
someObj.someFunc();
console.log("Global someFunc called " + someFunc.getCount() + " time" + (someFunc.getCount() > 1 ? "s" : "")) ;
console.log("Global someObj.someFunc called " + someObj.someFunc.getCount() + " time" + (someObj.someFunc.getCount() > 1 ? "s" : "")) ;
</script>
</head>
我覺得你忘了在你的文章中包含你的原始函數的輸出:) – acjay
我不知道接受哪個答案。 –
我發現這篇文章有用的時候瞭解JavaScript強制規則http://webreflection.blogspot.com/2010/10/javascript-coercion-demystified.html大部分規則是有意義的(我實際上喜歡0和「」是假的),但肯定會有一些地方會讓你感動 –