4 ms·
Can someone demonstrate the “objects as closures” concept they mention? I can’t find any references to it elsewhere online
by schickm11 4y ago
Can someone demonstrate the “objects as closures” concept they mention? I can’t find any references to it elsewhere online
- gildas 4y agoSee "Crockford Objects" here for example: https://levelup.gitconnected.com/crockford-objects-in-javascript-9947a65fc5e8#0795 https://levelup.gitconnected.com/crockford-objects-in-javasc...
- schickm11 4y agoThanks, that’s super clear. That’s such a simple technique when you compare it to using prototypes.
- kragen 4y agoThis function creates a closure with a private variable, "n". When invoked the closure will increase n by the specified amount, but there is no way to decrease it. const incfac = () => { let n = 0; return m => (m > 0 ? n += m : n) }; A more extensive example due to Norm Hardy, presuming a multiuser Scheme interpreter that supports ocap security, is this Scheme program for voting on where to have lunch: http://cap-lore.com/CapTheory/Language/Lunch.html http://cap-lore.com/CapTheory/Language/Lunch.html (define (mocntr) (let ((x 0)) (cons (lambda () (let ((yet #t)) (lambda () (if yet (begin (set! yet #f) (set! x (+ 1 x)) x))))) (lambda () x)))) (define lunchcrowd (list (lambda (x) (write (cons "for Bill" x))) (lambda (x) (write (cons "for Bob" x)) ((cdr (assoc "Mandarin" (cdr x))))))) (define restaurants (list "Mandarin" "Casa Lupe" "Coffee Shop")) (define (noontime) (let ((bb (map (lambda(r) (cons r (mocntr))) restaurants))) (for-each (lambda (e) (e (cons "Lunchtime!" (map (lambda(r)(cons (car r) ((cadr r)))) bb)))) lunchcrowd) (lambda ()(map (lambda(x) (cons (car x) ((cddr x)))) bb)))) You can translate this into current versions of ES straightforwardly but it doesn't get much more readable. Norm explains: > An invocation of mocntr is made each day for each restaurant. It returns a source of options, one of which will be offered to each of the lunch crowd. The second lambda in the definition produces such an option. The variable yet in that proc remembers if the option has been taken. The third lambda produces the getter for the count. > bb is created each day for lunch and constitutes the ballot box. It is a list of pairs <restuarant name, <option source, count getter>>. This list is iterated over first to send each vote solicitation, and then later to count the votes. Unfortunately he's vitrified now, so if you send him questions he will answer after a long delay, if ever.