raganwald / javascript-allonge

Markdown source for the book "JavaScript Allongé"
http://leanpub.com/javascript-allonge
760 stars 134 forks source link

i don't understand a sentence #77

Open nicoder opened 10 years ago

nicoder commented 10 years ago

Hi,

I don't understand this sentence in https://github.com/raganwald/javascript-allonge/blob/master/manuscript/markdown/Instances%20and%20Classes/recipes/named-once.md :

"As we noted when we saw the recipe for once, you do have to be careful that you are calling the function once returns multiple times."

loren-osborn commented 10 years ago

@nicoder,

once() is a decorator function that takes a function, and returns a function with the desired modified behavior. Many functions in this book immediately invoke the result of higher-order functions like decorators. Immediately invoking a returned function discards the function after a single invocation. As the whole point of the once() decorator is to intercept and prevent multiple invocations, immediate invocation discards any record or the function being previously executed with the discarded, decorated function, so the once() decorator will have no effect. You must store the decorated function for later use for it to have any effect. Similarly, (except for recursive execution) the memoize() decorator offers no benefit when immediately invoked either.

(@raganwald, it may be beneficial to have some way to differentiate the term "decorator"s as a subset of combinator functions, taking a single function as input, from the design pattern named "decorator" -- which many dynamic languages, like JavaScript, give you for free as a language feature. Anytime you are adding an arbitrary object property, that the "class" of the object isn't designed for, you are using the "decorator" design pattern.)

raganwald commented 10 years ago

it may be beneficial to have some way to differentiate the term "decorator"s as a subset of combinator functions, taking a single function as input, from the design pattern named "decorator" -- which many dynamic languages, like JavaScript, give you for free as a language feature. Anytime you are adding an arbitrary object property, that the "class" of the object isn't designed for, you are using the "decorator" design pattern.

Perhaps I may mention it. What interests me is what the two have in common, not how they differ. A similar pattern is the "trait," a mixin for a class that adds functionality without using any private object state.

nicoder commented 10 years ago

Thank you. I will try to be more precise : the second part of the sentence does not make sense to me : "you do have to be careful that you are calling the function once returns multiple times".

But maybe it is just because English is not my native language.