Question

It seems like in JavaScript functions which take in a function, modify behavior and return that function are decorators. For example, this would be a decorator function:

function doubleDec (func){
    return function(){
        return 2*func.apply(this, arguments)
    }
}
function sum(a, b) {
  return a + b
}

var doubleSum = doubleDec(sum)

alert(doubleSum(1,2))  //=> 6

But a decorator design pattern means you are taking in an object ...and modifying it?

Was it helpful?

Solution

Decorators are a generic pattern; it can mean multiple things depending on the domain.

They're also called "wrappers" or "adapters", which IMO is more applicable to the function wrapping paradigm. That said, don't get too hung up on precise wording: they're patterns, not immutable laws.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top