3 ms·
While I’ve never actually used `with()` that much, I do feel that it’s a lost opportunity b.c. `with()` was basically the only way to get dynamically scoped var
by goranmoomin 3y ago
While I’ve never actually used `with()` that much, I do feel that it’s a lost opportunity b.c. `with()` was basically the only way to get dynamically scoped variables (instead of lexically scoped ones) in JS (and tbh, in other ALGOL-derived languages as well).
Dynamically scoped variables are a much better solution to global variables… so for example, in Common Lisp you can have a STANDARD-OUTPUT variable that you can use to log things in your code, and then if you want to temporarily redirect your logs to a file, you can just do:
(let ((*STANDARD-OUTPUT* file))
(your-code-runs-here))
And the code in the block will automatically redirect your output to the file.
- lolinder 3y ago`with` is still lexically scoped—it just adds another scope to the lexical scope chain. The variables are still scoped to the beginning and end of a particular block of code, and if that code calls out to a function that was defined outside of that block the variables don't follow to that called function (unless explicitly passed as arguments). From what I can tell, your CL example is truly dynamically scoped (assuming the global is defined with `defvar`)—functions defined outside of that `let` form will still use the version you give in the `let` when they're called inside that call tree. Where JavaScript does have a bit of dynamic scoping is with `this`. All OOP languages technically use dynamic scope for `this`, but JavaScript even more so since `this` can be rebound arbitrarily.
- kazinator 3y agoIf with defines variables which are not mentioned in it explicitly, and which are controlled by an entirely different part of the program, possibly in another file, we can make the argument that it is not actually lexically scoped.