Javascript как сделать переменную глобальной

Javascript как сделать переменную глобальной

The var statement declares function-scoped or globally-scoped variables, optionally initializing each to a value.

Try it

Syntax

var name1; var name1 = value1; var name1 = value1, name2 = value2; var name1, name2 = value2; var name1 = value1, name2, /* …, */ nameN = valueN; 

The name of the variable to declare. Each must be a legal JavaScript identifier.

Initial value of the variable. It can be any legal expression. Default value is undefined .

The destructuring syntax can also be used to declare variables.

var  bar > = foo; // where foo = < bar: 10, baz: 12 >; // This creates a variable with the name 'bar', which has a value of 10 

Description

The scope of a variable declared with var is one of the following curly-brace-enclosed syntaxes that most closely contains the var statement:

Or if none of the above applies:

  • The current module, for code running in module mode
  • The global scope, for code running in script mode.
function foo()  var x = 1; function bar()  var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) > bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // ReferenceError, `y` is scoped to `bar` > foo(); 

Importantly, other block constructs, including block statements, try. catch , switch , headers of one of the for statements, do not create scopes for var , and variables declared with var inside such a block can continue to be referenced outside the block.

for (var a of [1, 2, 3]); console.log(a); // 3 

In a script, a variable declared using var is added as a non-configurable property of the global object. This means its property descriptor cannot be changed and it cannot be deleted using delete . JavaScript has automatic memory management, and it would make no sense to be able to use the delete operator on a global variable.

"use strict"; var x = 1; Object.hasOwn(globalThis, "x"); // true delete globalThis.x; // TypeError in strict mode. Fails silently otherwise. delete x; // SyntaxError in strict mode. Fails silently otherwise. 

In both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not added as properties to the global object.

The list that follows the var keyword is called a binding list and is separated by commas, where the commas are not comma operators and the = signs are not assignment operators. Initializers of later variables can refer to earlier variables in the list and get the initialized value.

Hoisting

var declarations, wherever they occur in a script, are processed before any code within the script is executed. Declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it’s declared. This behavior is called hoisting, as it appears that the variable declaration is moved to the top of the function, static initialization block, or script source in which it occurs.

Note: var declarations are only hoisted to the top of the current script. If you have two elements within one HTML, the first script cannot access variables declared by the second before the second script has been processed and executed.

This is implicitly understood as:

For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it’s clear which variables are scoped to the current function.

Only a variable’s declaration is hoisted, not its initialization. The initialization happens only when the assignment statement is reached. Until then the variable remains undefined (but declared):

function doSomething()  console.log(bar); // undefined var bar = 111; console.log(bar); // 111 > 

This is implicitly understood as:

function doSomething()  var bar; console.log(bar); // undefined bar = 111; console.log(bar); // 111 > 

Redeclarations

Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value, unless the declaration has an initializer.

var a = 1; var a = 2; console.log(a); // 2 var a; console.log(a); // 2; not undefined 

var declarations can also be in the same scope as a function declaration. In this case, the var declaration’s initializer always overrides the function’s value, regardless of their relative position. This is because function declarations are hoisted before any initializer gets evaluated, so the initializer comes later and overrides the value.

var a = 1; function a() > console.log(a); // 1 

var declarations cannot be in the same scope as a let , const , class , or import declaration.

var a = 1; let a = 2; // SyntaxError: Identifier 'a' has already been declared 

Because var declarations are not scoped to blocks, this also applies to the following case:

let a = 1;  var a = 1; // SyntaxError: Identifier 'a' has already been declared > 

It does not apply to the following case, where let is in a child scope of var , not the same scope:

A var declaration within a function’s body can have the same name as a parameter.

function foo(a)  var a = 1; console.log(a); > foo(2); // Logs 1 

A var declaration within a catch block can have the same name as the catch -bound identifier, but only if the catch binding is a simple identifier, not a destructuring pattern. This is a deprecated syntax and you should not rely on it. In this case, the declaration is hoisted to outside the catch block, but any value assigned within the catch block is not visible outside.

try  throw 1; > catch (e)  var e = 2; // Works > console.log(e); // undefined 

Источник

Локальные и глобальные переменные в JavaScript

Глобальные переменные – это такие, которые объявлены в глобальной области видимости. То есть вне блока, функции и модуля.

// глобальная переменная сar let car = 'Audi';

Глобальная переменная доступна в любой части кода, только если она не пересекается с локальной переменной.

Доступ к глобальной переменной year внутри myFunc() :

// глобальные переменные car и year let car = 'Audi'; let year = 2007; function myFunc() { // локальная переменная car let car = 'Ford'; console.log(car); // "Ford" console.log(year); // 2007 } myFunc(); // "Audi"

Внутри функции myFunc() мы не сможем получить доступ к глобальной переменной car после объявления переменной с таким же именем внутри этой функции.

// глобальная переменная numberUsers let numberUsers = 0; // объявление функции addUsers const addUsers = (num) => { numberUsers += num; return numberUsers; } console.log(addUsers(5)); // 5 console.log(addUsers(2)); // 7 console.log(numberUsers); // 7

В это примере мы нарушили одно из ключевых правил: поменяли внутри функции значение внешней переменной. Это делать крайне не рекомендуется.

Локальные переменные

Локальные переменные – это такие, которые объявлены в локальной области видимости. Например, внутри блока {. } :

{ // количество просмотров let totalViews = 10; }

Локальные переменные имеют локальную область действия, т.е. они не будут доступны за пределами той области, в которой объявлены:

{ // количество просмотров let totalViews = 10; } console.log(totalViews); // Uncaught ReferenceError: totalViews is not defined

Локальные переменные с одними и теми же именами могут использоваться в разных блоках:

if (true) { let pageTitle = 'Учебник по JavaScript'; console.log(pageTitle); // "Учебник по JavaScript" } if (!false) { let pageTitle = 'Учебник по CSS'; console.log(pageTitle); // "Учебник по CSS" }

Локальные переменные доступны в других локальных областях видимости, созданных внутри этой:

if (true) { // количество просмотров let totalViews = 10; let addViews = () => { totalViews++; return totalViews; } if (totalViews) { addViews(); console.log(totalViews); // 11 } }

Жизненный цикл переменных

Рассмотрим жизненный цикл переменных a и b на следующем примере:

let a = 7; let b; const someFunc = () => { let b; a = null; b = 5; console.log(b); } someFunc(); console.log(a); console.log(b);

В этом примере мы объявили переменным a , b и someFunc в глобальной области видимости. Следовательно, эти переменные являются глобальными.

Переменной someFunc мы присвоили функциональное выражение. Далее мы вызвали эту функцию, используя данную переменную.

При вызове функции someFunc() создастся локальная область видимости функции. В этой области видимости мы объявили переменную b . Следовательно, эта переменная локальная.

При этом новая локальная область будет создаваться каждый при вызове someFunc() .

Жизненный цикл переменной a

1. Сначала переменная a объявляется в глобальной области видимости и ей сразу же с помощью оператора = присваивается число 7.

2. Вызов someFunc() создаёт локальную область видимости функции, которая содержит ссылку на глобальную область видимости. Здесь мы пытаемся присвоить переменной a значение null . Т.к. a в этой области нет, то мы переходим по ссылке к внешней области видимости, которая в данном случае является глобальной, и ищем переменную здесь. Здесь мы её находим и присваиваем ей новое значение, т.е. null .

Таким образом после выполнения этой строчки глобальная переменная a будет иметь значение null . Т.е. мы поменяли значение внешней переменной внутри функции.

3. После выполнения функции someFunc она возвращает значение undefined . Все локальные переменные, которые были созданы внутри неё больше не доступны и сборщик мусора их удаляет.

На следующем шаге, когда мы пытаемся вывести значение переменной a в консоль, интерпретатор находит её в текущей области видимости, которая является глобальной. При этом значение переменной уже не 7 , а null . Значение a мы изменили внутри функции.

Жизненный цикл переменной b

1. Переменная с именем b создаётся в глобальной области видимости. На этом шаге её значение undefined , т.к. ей не было присвоено значение.

2. При вызове функции someFunc() создаётся локальная область. В ней объявляется переменная b посредством let .

3. Затем на строке b = 5 хотим присвоить переменной b число 5 . Но сначала необходимо найти переменную b . Поиск переменной всегда начинается с текущей области видимости. В ней она есть. Следовательно берем её и присваиваем ей значение 5 . Т.е. мы присвоили значение локальной переменной, не глобальной.

4. На следующем шаге ( console.log(b) ) мы хотим вывести значение переменной b в консоль. Для того чтобы это сделать, нам нужно снова найти эту переменную. В данном случае мы её находим в области видимости функции и у этой переменной значение 5, которое мы ей присвоили ей на строке b = 5 . Следовательно, в консоль выведется значение 5 .

После этого функция someFunc() завершает свою работу. Она возвращает undefined . Но этот результат мы не кому не присваиваем и никуда не выводим.

5. Печатаем в консоль значение переменной b . Но чтобы это сделать нужно найти эту переменную. Сейчас мы находимся в глобальной области видимости и поэтому поиск нужно начинать отсюда. Здесь эта переменная имеет значение undefined , поэтому мы и увидим его в консоли.

Основные правила работы с переменными

Основные моменты, которые необходимо знать при работе с переменными в JavaScript:

  • Включение строгого режима запрещает автоматическое создание не объявленных переменных;
  • Переменные необходимо объявлять перед тем как их использовать;
  • Создавать переменные необходимо посредством const там где это возможно. А let использовать для объявления только тех переменных, которым вы планируете потом присваивать новые значения;
  • Объявлять переменные в глобальной области видимости крайне не желательно, количество таких переменных рекомендуется свести к минимуму;
  • Функции стараться писать так, чтобы они не изменяли внешние переменные.

Источник

Читайте также:  Простейший код в php
Оцените статью