[proposal] Persistent variables in functions/methods
Jacob Pratt
jhprattdev at gmail.com
Tue Jul 17 05:06:37 UTC 2018
Can you explain the difference between this and static properties? At quick
glance, I don't see any.
Would this not work?
```javascript
function foo(n) {
this.counter++;
return n * a;
}
foo.counter = 0;
foo.httpRE = /^https?/;
```
jhpratt
On Tue, Jul 17, 2018 at 12:56 AM, Neek Sandhu <neek.sandhu at outlook.com>
wrote:
> It'd be really useful to have variables inside methods/functions that are
> initialized once, reused for subsequent calls and live as long as
> containing scope i.e the function itself.
>
> > not to be confused with `static` properties
>
> ## Use Cases
>
> Almost every app has a function or method that needs to "preserve" some
> state across multiple calls, a counter for example. Current ways out of
> this situation are either closures created with IIFE's or making those
> variables top-level. Both of which are ugly. I think the same could be done
> much more neatly with persistent variables.
>
> ## Example
>
> ```javascript
> function foo(n) {
> // initialized on first call to foo, persists for subsequent calls
> persist let counter = 0;
>
> // this way JS engine won't have to recompile the pattern everytime
> persist const httpRE = /^https?/;
>
> counter++;
> return n * a;
> }
> ```
>
> is 1:1 as
>
> ```javascript
> let foo = (() => {
> let counter = 0;
> const httpRE = /^https?/;
> return (n) => {
> counter++;
> return n * a;
> }
> })()
> ```
>
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180717/d0ffb9b3/attachment.html>
More information about the es-discuss
mailing list