From Javascript's kiss
var countInner = 0;
var countOuter = 0;
var countMid = 0;
var addListener = function(el, type, handle){
//在这里也是重新定义addListener方法
countOuter++; //计算外部的函数将会执行多少次
addListener = (function(){
if (el.addEventListener) {
countMid++; //计算if下将会执行多少次,下同
return function(el, type, handle){
countInner++; //计算内部的函数将会执行多少次,下同
el.addEventListener(type, handle, false);
};
} else
if (el.attachEvent) {
countMid++;
return function(el, type, handle){
countInner++;
el.attachEvent("on" + type, function(e){
handle.call(el, e);
});
};
} else {
countMid++;
return function(el, type, handle){
countInner++;
el["on" + type] = handle;
};
}
})();
addListener(el, type, handle);
}
var benchmark = function(fn, times){
var d1 = new Date(), d2, n;
while (times--)
n = fn();
var d2 = new Date();
return d2.getTime() - d1.getTime();
}
alert(benchmark(function(){
var rand = Math.random() * 100000;
var div = document.createElement("div");
div.id = "div" + rand;
div.innerHTML = "div text" + rand;
addListener(div, "click", function(e){
alert(this.id);
});
document.body.appendChild(div);
}, 1000));
alert(countInner);
alert(countOuter);
alert(countMid);