Re:JavaScript Getter-Setter Pyramid
by SeanLuke on Wednesday December 19, 2018 @10:51AM
(#18716439)
I'm interested in this simple closure code from the article:
As a lisp coder [and not a JS coder], I'm wondering: why does the function getNext() have to be named? Why not just say something like:
[ Parent
| on HN ]
Re:JavaScript Getter-Setter Pyramid
by kangoo1707 on Wednesday December 19, 2018 @10:54AM
(#18716465)
It doesn't have to be named, your second example still works
naming anonymous functions can provide some clarity in stack traces however
I got the syntax right? Was completely guessing.
Re:JavaScript Getter-Setter Pyramid
by basil-rash on Wednesday December 19, 2018 @02:55PM
(#18718913)
Yep. Nowadays you'd be more likely to see it as:
return () => {
const next = i;
i = i * 2;
return next;
}
But in this case the two are equivalent.
Re:JavaScript Getter-Setter Pyramid
by interesthrow2 on Wednesday December 19, 2018 @05:08PM
(#18720234)
Or as an alternative one can use a generator, they are built for that purpose AND are supported by a wide range of other JS constructs without any need to create iterators manually and all that.
function * getNext(){
let i = 2;
while(true){
i = i * 2;
yield i;
}
}
Here, no closure needed.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guid...
I think that's no longer getter-getter and the example was to show a function that explicitly returns a function.