Skip to content

Instantly share code, notes, and snippets.

@mknln
Created November 13, 2013 06:11
Show Gist options
  • Save mknln/7444512 to your computer and use it in GitHub Desktop.
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.
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