1、使用继承:
function Foo(){ } Foo.prototype.doSomething = function(){ console.log('Foo method was called'); }; function Decorator(){ Foo.apply(this, arguments); } Decorator.prototype = Object.create(Foo.prototype); Decorator.prototype.constructor = Decorator; Decorator.prototype.doSomething = function(){ console.log('Before'); return Foo.prototype.doSomething.apply(this, arguments);//被装饰的方法 }; var obj = new Decorator(); obj.doSomething();2、AOP(面向切面)方法:
function Bar(){ } Bar.prototype.doSomething = function (){ console.log("Bar's method was called"); }; function Decorator(obj, method){ var origMethod = obj[method]; obj[method] = function(){ console.log('Before'); var ret = origMethod.apply(this, arguments); console.log('After'); return ret; }; } var bar = new Bar(); Decorator(bar, 'doSomething'); bar.doSomething();