Created
November 13, 2013 06:11
-
-
Save mknln/7444512 to your computer and use it in GitHub Desktop.
Reading JavaScript Patterns I thought of another way to write the decorator pattern.
Not yet sure if this has any pitfalls.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
SalesOrder.prototype.decorate = function(decorator) { | |
var override | |
for (override in decorator) { | |
if (decorator.hasOwnProperty(override)) { | |
var oldfunc = this[override] | |
var decfunc = decorator[override] | |
var newfunc = function() { | |
var args = Array.prototype.slice.call(arguments) | |
return decfunc.call(this, oldfunc.apply(this, args)) | |
} | |
this[override] = newfunc | |
} | |
} | |
} | |
SalesOrder.decorators = {} | |
SalesOrder.decorators.tax = { | |
getPrice: function(p) { | |
return p * 1.08 | |
} | |
} | |
function SalesOrder() { | |
this.getPrice = function() { | |
return 12.88 | |
} | |
} | |
//var sale = new SalesOrder() | |
//sale.decorate(SalesOrder.decorators.tax) | |
//console.log(sale.getPrice()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment