简体   繁体   中英

How can function reference itself within itself in JavaScript?

I understand recursion in terms of how code is executed and why you might need it. What I am wondering about is that is it possible that function can reference itself within itself?

Given the following example:

function factorial(num) {
  if(num ===0) {
    return 1
  }
  return (num * factorial(num - 1));
}

factorial(2)

I want to understand what is happening under the hood in terms of how variables are stored in memory and how they're called and why is it possible to reference factorial inside a factorial function.

The way I understand how it is going to be executed at the moment:

  1. Declare a function factorial on the stack that will reference an object on the heap. At this moment factorial still points to nowhere
  2. Create an object on the heap(function) that will calculate factorial
  3. Call factorial(2) which will take the reference on the stack where factorial points to, find the function on the heap and call it.

What I don't understand is that how when factorial is called, will it know what is factorial and where to find it? Is it related to closures somehow?

Another example(jest)

  const someFunction = jest.fn((value) => {
    expect(someFunction).toHaveBeenCalled()
  })

Why I can reference someFunction inside the someFunction , as mentioned I suspect it is related to memory and how variables are stored, but I don't grasp the concept fully.,

By using a named function declaration/ expression , the call checks the inner scope of the function and if it is not inside, it check the name of the called function and then the outer scope.

However, a name can be provided with a function expression. Providing a name allows the function to refer to itself, and also makes it easier to identify the function in a debugger's stack traces

By using arrow functions , the name of function is not set and does not remain by renaming as opposite of a named function declaration, where the name is always callable from the inner scope.

The Function Guide of the MDN Web Docs contains the information you seek. There are multiple ways you can reference a function from inside its body. It boils down to the fact, that

a function can access all variables and functions defined inside the scope in which it is defined

You can read this as a function can access everything defined in the scope in which it was defined. This includes itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM