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

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

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?

Était-ce utile?

La 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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top