What is the difference between a "decorator function" and "decorator design pattern" in JavaScript?

StackOverflow https://stackoverflow.com/questions/21414506

Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top