替代模型是近似 JavaScript 如何评估纯代码的好方法吗?

Is the substitution model a good way of approximating how JavaScript evaluates pure code?

假设这是我的程序:

let f = x => x * 2
let g = x => f(x) + 1
let h = x => g(x) > 3
h(2)

对于 JS 运行时如何评估这段代码,替换模型是一个很好的心理模型,还是它实际评估的方式非常不同?

https://en.wikipedia.org/wiki/Lambda_calculus#Substitution https://en.wikipedia.org/wiki/Referential_transparency

Is the substitution model a good way of approximating how JavaScript evaluates pure code?

当然可以!

let f = x => x * 2
let g = x => f(x) + 1
let h = x => g(x) > 3

h(2)
// = ...
// substitute h with its definition

(x => g(x) > 3) (2)
// substitute x with 2

g(2) > 3
// substitute g with its definition

(x => f(x) + 1) (2) > 3
// substitute x with 2

f(2) + 1 > 3
// substitute f with its definition

(x => x * 2) (2) + 1 > 3
// substitute x with 2

2 * 2 + 1 > 3
// apply * to 2 and 2

4 + 1 > 3
// apply + to 4 and 1

5 > 3
// apply > to 5 and 3

<b>true</b>

I understand how to apply the substitution model to my code - my question is how this is different from how real JS runtimes (V8, etc.) evaluate it.

你的问题是 evaluation strategy is JavaScript using – JavaScript uses call by sharing 但当然你仍然可以使用替代模型来得出答案 使用 通过共享评估策略调用。

替代模型不会强制您使用一种策略代替另一种策略。事实上,在(几乎)所有情况下,如果你使用纯函数,评估策略并不重要——答案是一样的

尽管结果相同,但评估方式大不相同。要设想的最相关的纯 CS 模型是 environment model。简而言之,当一个语句被评估时,它可能会改变它当时拥有的引用。这些突变是通过 JS 中的作用域链管理的,但这本质上只是上述环境的另一个名称。