装饰者模式擅长为各种对象添加新特性: 本例创建的装饰者可以用来馐任何对象,以便于为其提供方法性能分析. 一个用来测试的类 var ListBuilder = function(parent, listLength){ this.parentEl = document.getElementById(parent); this.listLength = listLength; } ListBuilder.prototype = { buildList : function(){ var list = document.createElement("ol"); this.parentEl.appendChild(list); for(var i=0; i<this.listLength; i++){ var item = document.createElement("li"); list.appendChild(item); } }, buildList2 : function(){ var s = ""; for(var i=0; i<1000000; i++){ s = s + "a"; } } } 分析器: var MethodProfiler = function(component){ this.component = component; this.timers = {}; //循环检查对象的属性,如果是方法,则为装饰者添加一个同名的方法,并启动计时器 for(var key in this.component){ if(typeof this.component[key] !== "function"){ continue; } var that = this; (function(methodName){ that[methodName] = function(){ that.startTimer(methodName); var returnValue = that.component[methodName].apply(that.component,arguments); that.displayTime(methodName,that.getElapsedTime(methodName)); return returnValue; } })(key) } } MethodProfiler.prototype = { startTimer : function(methodName){ this.timers[methodName] = (new Date()).getTime(); }, getElapsedTime : function(methodName){ return (new Date()).getTime() - this.timers[methodName]; }, displayTime : function(methodName, time){ console.log(methodName + " : " + time + " ms"); } }