Closures are just a poor mans object.
(Not sure where this quote is from originally? Maybe here: http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/m...)
Closures are just a poor mans object.
(Not sure where this quote is from originally? Maybe here: http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/m...)
(define (cons x y)
(lambda (m) (m x y)))
(define (car z)
(z (lambda (p q) p)))
(define (cdr z)
(z (lambda (p q) q)))
Here, cons, instead of returning an object with two values, returns a closure that captures the two values. car and cdr call that closure, passing it another closure. The cons closure calls that closure, passing the the two values.Explanation at https://stackoverflow.com/questions/21769348/use-of-lambda-f....
Of course, it completely kills (or "stress-tests", if you will) the branch predictor in your CPU.
My exact quote was, While closures may look like a poor man's object, I think the reverse is closer to the case.
You can do it with metatable manipulation as well(changing the functions which map to specific table operators which lets you change how unmapped keys are handled) but I found the lexical closures to make a lot more sense.
As far as I know, yes, that's the oldest I've been able to find.
function Person(firstName, lastName) {
let fName = firstName;
let lName = lastName;
public getFullName = function() {
return fName + ' ' + lName;
};
public setFirstName = function(firstName) {
fName = firstName;
};
return this;
}
("return this" is probably not the best syntax at the end there, especially if bolting this onto javascript.)I would use “return scope”.
Link because this describes it more thoroughly and more precisely than I can.
The compiler will generate a class with fields for whatever variables are captured, and then instantiate it for you, assign the fields etc.
If you define your function reference as a type (as it's called), you can even inherit[1] from it and add additional overloads to the inherited class, to make it do multiple things.
[1]: https://delphisorcery.blogspot.com/2015/06/anonymous-method-...