This becomes really powerful when you notice that many of your functions are either doing the exact same thing, or essentially the same thing, either when they begin execution or finish, for example, many of them might be making sure that the number the user entered is in within a certain range. Without decorators, we have to write this checking into each separate function that we write. With a decorator function, however, we place this checking in the decorator instead, write the rest of each function, and call the decorator on those functions.
Take for example, the isInRangeDec decorator function shown below. It takes a lowerBound, upperBound and a function f and then uses these to define a new function which it ultimately returns. Note that this new function is also a closure, which means that it has its own environment, because it captures state in the parameters lowerBound and upperBound.
The new function created by the isInRange decorator iterates over its arguments, via the special arguments array checking whether each is a number. When it finds one that is, it then checks that it is within the range defined by lowerBound and upperBound. If the argument is in range, then the function returns the result of applying the function f to those arguments. If it is not in range, then the function raises an alert to inform the user and returns undefined.
Of course, in this case, you could also encapsulate the checking in a function of its own and simply call that function from within the functions that you are writing. The only thing is that would mean that you would have to write the call to the checking function into the body of all the other functions. And interestingly, that is essentially what the decorator is doing. The decorator is writing the call to one function into the body of the other function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var isInRangeDec = function(lowerBound, upperBound, f){ return function(){ for(var i=0; i < arguments.length; ++i){ if(typeof Number(arguments[i]) === 'number'){ var x = Number(arguments[i]); if(x < lowerBound || upperBound < x){ var messagePart1 = 'Please enter a number in the range '; var messagePart2 = lowerBound + ' to ' + upperBound; alert(messagePart1 + messagePart2); return; } } } return f.apply(this, arguments); } } |












