M
M
Maxim2018-01-16 23:13:13
JavaScript
Maxim, 2018-01-16 23:13:13

How does a function access itself when called recursively?

Is it correct to say that when a function is called recursively in code, the js engine looks for the declaration of the called function in the outer scope? Below is the code with comments.

function func() {  //функция func объявлена в глобальном контексте
    func(); 
/*в текущей области видимости 'func' не объявлена, поэтому движок 
ищет объявление во внешней области видимости (в данном случае это
 глобальная область видимости), находит его там и теперь может выполнить функцию*/
}

Getting access to variables and functions occurs approximately as I described above (we immediately look inside the current scope, then we go in turn to look in external ones). Is this logic suitable for recursive calls, or do they follow their own "laws"?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Spirin, 2018-01-16
@Melagomania

Everything is correct https://jsfiddle.net/yy38x0mg/
This logic is valid for any calls.

S
Stalker_RED, 2018-01-16
@Stalker_RED

In js, if something is not declared, it always looks in the outer scope.
You can read more here: https://learn.javascript.ru/closures

D
Dmitry Belyaev, 2018-01-17
@bingo347

'func' is not declared in the current scope

just announced. In any named function, its name is created at the time of the call (along with arguments and this) and refers to the function itself. This is most clearly shown by named function expressions:
var f = function func() {
  console.log(func.name); // 'func'
};
console.log(f.name); // 'func'
console.log(func.name); // Reference error так как func нет в этой области видимости

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question