简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM