JavaScript: Functions, Execution Context and Variables scopes
Variable Scoping
в JS область видимости - это текущий контекст в коде.
глобальная область видимости
локальная область видимости (функция)
блочная область видимости для переменных (let, const)
LexicalEnvironment
Все переменные внутри функции – это свойства специального внутреннего объекта LexicalEnvironment. При запуске функция создает объект LexicalEnvironment, записывает туда аргументы, функции и переменные.
Каждая функция при создании получает ссылку [[Scope]] на объект с переменными, в контексте которого была создана.
При запуске функции создаётся новый объект с переменными LexicalEnvironment. Он получает ссылку на внешний объект переменных из [[Scope]].
При поиске переменных он осуществляется сначала в текущем объекте переменных, а потом – по этой ссылке.
Context of calling
Context - это не scope, а то, куда ссылается
this
this
Значение this называется контекстом вызова и будет определено в момент вызова функции.
this - текущий объект при вызове «через точку» и новый объект при конструировании через new.
Если одну и ту же функцию запускать в контексте разных объектов, она будет получать разный this
потеря контекста
Functions
Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
A function declaration looks like this:
Values passed to a function as parameters are copied to its local variables. A variable declared inside a function is only visible inside that function.
A function may access outer variables. But it works only from inside out.
The function has full access to the outer variable. It can modify it as well.
The code outside of the function doesn’t see its local variables.
A function can return a value. If it doesn’t, then its result is
undefined
.
To make the code clean and easy to understand, it’s recommended to use mainly local variables and parameters in the function, not outer variables.
We can pass arbitrary data to functions using parameters (also called function arguments) .
When the function is called in lines (*)
and (**)
, the given values are copied to local variables from
and text
. Then the function uses them.
Here’s one more example: we have a variable from
and pass it to the function. Please note: the function changes from
, but the change is not seen outside, because a function always gets a copy of the value:
It is always easier to understand a function which gets parameters, works with them and returns a result than a function which gets no parameters, but modifies outer variables as a side-effect.
If a parameter is not provided, then its value becomes undefined
.
For instance, the aforementioned function showMessage(from, text)
can be called with a single argument:
That’s not an error. Such a call would output "Ann: undefined"
. There’s no text
, so it’s assumed that text === undefined
.
If we want to use a “default” text
in this case, then we can specify it after =
:
Function naming:
A name should clearly describe what the function does. When we see a function call in the code, a good name instantly gives us an understanding what it does and returns.
A function is an action, so function names are usually verbal.
There exist many well-known function prefixes like
create…
,show…
,get…
,check…
and so on. Use them to hint what a function does.
Functions are the main building blocks of scripts. Now we’ve covered the basics, so we actually can start creating and using them. But that’s only the beginning of the path. We are going to return to them many times, going more deeply into their advanced features.
Execution Context
A property of an execution context (global, function or eval) that, in non–strict mode, is always a reference to an object and in strict mode can be any value.
Global context
In the global execution context (outside of any function), this
refers to the global object whether in strict mode or not.
You can always easily get the global object using the global globalThis
property, regardless of the current context in which your code is running.
Function context
Inside a function, the value of this
depends on how the function is called.
Since the following code is not in strict mode, and because the value of this
is not set by the call, this
will default to the global object, which is window
in a browser.
In strict mode, however, if the value of this
is not set when entering an execution context, it remains as undefined
, as shown in the following example:
In the second example, this
should be undefined
, because f2
was called directly and not as a method or property of an object (e.g. window.f2()
). This feature wasn't implemented in some browsers when they first started to support strict mode. As a result, they incorrectly returned the window
object.
Variables scopes
The scope of a variable is the region of your program source code in which it is defined. A global variable has global scope; it is defined everywhere in your JavaScript code. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables and have local scope.
Within the body of a function, a local variable takes precedence over a global variable with the same name. If you declare a local variable or function parameter with the same name as a global variable, you effectively hide the global variable:
Although you can get away with not using the var statement when you write code in the global scope, you must always use var to declare local variables. Consider what happens if you don’t:
Function definitions can be nested. Each function has its own local scope, so it is possible to have several nested layers of local scope. For example:
Function Scope and Hoisting
Function hoisting
Hoisting is JavaScript's default behavior of moving declarations to the top.
Variables and constants declared with let or const are not hoisted!
function declaration, var - hoisted
In some C-like programming languages, each block of code within curly braces has its own scope, and variables are not visible outside of the block in which they are declared. This is called block scope, and JavaScript does not have it. Instead, JavaScript uses function scope: variables are visible within the function in which they are defined and within any functions that are nested within that function. In the following code, the variables i, j, and k are declared in different spots, but all have the same scope—all three are defined throughout the body of the function:
JavaScript’s function scope means that all variables declared within a function are visible throughout the body of the function. Curiously, this means that variables are even visible before they are declared. This feature of JavaScript is informally known as hoisting: JavaScript code behaves as if all variable declarations in a function (but not any associated assignments) are “hoisted” to the top of the function. Consider the following code:
You might think that the first line of the function would print “global”, because the var statement declaring the local variable has not yet been executed. Because of the rules of function scope, however, this is not what happens. The local variable is defined throughout the body of the function, which means the global variable by the same name is hidden throughout the function. Although the local variable is defined throughout, it is not actually initialized until the var statement is executed. Thus, the function above is equivalent to the following, in which the variable declaration is “hoisted” to the top and the variable initialization is left where it is:
In programming languages with block scope, it is generally good programming practice to declare variables as close as possible to where they are used and with the narrowest possible scope. Since JavaScript does not have block scope, some programmers make a point of declaring all their variables at the top of the function, rather than trying to declare them closer to the point at which they are used. This technique makes their source code accurately reflect the true scope of the variables.
Last updated