2

我正在阅读Kyle Simpson的You don't know JS的Scopes and Closure标题,特别是这个主题Compiler Speak。本节介绍引擎使用的查找类型。现在我在本节给出的范围内了解什么是 LHS 或 RHS 查找。

我的问题是说明表单的函数声明function fx(a) {..不是 LHS 查找。有相同的解释,但我无法理解。这是整个笔记

您可能很想将函数声明函数概念化foo(a) {...为普通的变量声明和赋值,例如var fooand foo = function(a){...。这样做时,很容易将此函数声明视为涉及 LHS 查找。然而,微妙但重要的区别在于,编译器在代码生成期间同时处理声明和值定义,这样当引擎执行代码时,不需要处理将函数值“分配”给foo. 因此,以我们在这里讨论的方式将函数声明视为 LHS 查找分配是不合适的。

任何形式的澄清都会有所帮助。即使在 LHS 和 RHS 查找中。

4

2 回答 2

2

“查找”的主题与表达式评估有关。函数声明语句

function someName() {
  // code
}

不是表达式。它是一种不同的语句类型,与作为一种不同的语句类型的方式相同return, andwhileif。函数声明语句中不会发生表达式求值,除了隐式实例化要绑定到本地范围内的函数名称的新函数对象。

LHS 和 RHS 值的主题(根据我的经验,通常在文献中称为l 值r 值)很重要,但它与函数声明无关。

于 2015-10-27T14:32:50.707 回答
1

I shared the same question while reading. Pointy's answer above made the concept pretty clear, and I am just adding more explanation using the quote from a newer edition of the book:

"function getStudentName(studentID) {

A function declaration is a special case of a target reference. You can think of it sort of like var getStudentName = function(studentID), but that's not exactly accurate. An identifier getStudentName is declared (at compile time), but the = function(studentID) part is also handled at compilation; the association between getStudentName and the function is automatically set up at the beginning of the scope rather than waiting for an = assignment statement to be executed.

NOTE: This automatic association of function and variable is referred to as "function hoisting", and is covered in detail in Chapter 5."

Here is the link to the new edition on GithHub.

于 2020-12-06T22:52:02.703 回答