JavaScript: Переменные и константы. Соглашения о коде языка JavaScript Присвоение значения переменным

Когда в программе необходимо сохранить значение, чтобы использовать его позже, это значение присваивается переменной. Переменная – это просто символьное имя для значения, которое обеспечивает возможность получить значение по имени, то есть, когда в программе указывается имя переменной вместо неё подставляется значение.

Переменная получила своё название благодаря тому, что её значение может быть изменено по ходу выполнения программы.

Константы

Константа – это просто символьное имя для значения. Константа даёт возможность обратиться к значению по имени, это означает, что, когда в программе указывается имя константы, вместо неё подставляется значение. Константы используются для хранения данных, которые не должны изменяться во время выполнения программы.

Прежде чем использовать константу, её необходимо объявить. Константы объявляются с помощью ключевого слова const , за которым следует имя константы. Чтобы в коде программы отличать константы от переменных, константам условились давать имена написанные заглавными буквами:

Const MAX = 10;

После того как константа создана, попытка переопределить её на переменную или попытка присвоить существующей константе значение вызовет ошибку.

Зачем нужны переменные и константы

Переменные и константы помогают сделать программный код понятнее. Рассмотрим небольшой пример:

TotalPrice = 2.42 + 4.33; // Общая цена

Имеющиеся здесь числа могут означать что угодно. Чтобы стало понятно, что именно здесь суммируется, значение 2.42 можно присвоить переменной (или константе) candyPrice (цена конфет), а 4.33 - переменной (или константе) oilPrice (цена масла):

TotalPrice = candyPrice + oilPrice;

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

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

Область видимости констант

К константам применяются те же правила, что и к переменным, объявленным с помощью ключевого слова let:

Const MAX = 5; // Глобальная константа { const MAX = 10; // Блочная константа console.log(MAX); // 10 } console.log(MAX); // 5 foo(); // 15 console.log(MAX); // 5 function foo() { const MAX = 15; // Локальная константа console.log(MAX); }

Константы и ссылочные типы

Когда константе присваивается значение ссылочного типа, то неизменяемой становится ссылка на значение, а само значение остаётся доступным для изменений:

Const obj = {a: 5}; obj.a = 10; console.log(obj.a); // 10

Последнее обновление: 05.04.2018

Для хранения данных в программе используются переменные . Переменные предназначены для хранения каких-нибудь временных данных или таких данных, которые в процессе работы могут менять свое значение. Для создания переменных применяются ключевые слова var и let . Например, объявим переменную myIncome:

Var myIncome; // другой вариант let myIncome2;

Каждая переменная имеет имя. Имя представляет собой произвольный набор алфавитно-цифровых символов, знака подчеркивания (_) или знака доллара ($), причем названия не должны начинаться с цифровых символов. То есть мы можем использовать в названии буквы, цифры, подчеркивание. Однако все остальные символы запрещены.

Например, правильные названия переменных:

$commision someVariable product_Store income2 myIncome_from_deposit

Следующие названия являются некорректными и не могут использоваться:

222lol @someVariable my%percent

Также нельзя давать переменным такие имена, которые совпадают с зарезервированными ключевыми словами. В JavaScript не так много ключевых слов, поэтому данное правило не сложно соблюдать. Например, следующее название будет некорректным, так как for - ключевое слово в JavaScript:

Var for;

Список зарезервированных слов в JavaScript:

abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, inteface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with

При названии переменных надо учитывать, что JavaScript является регистрозависимым языком, то есть в следующем коде объявлены две разные переменные:

Var myIncome; var MyIncome;

Через запятую можно определить сразу несколько переменных:

Var myIncome, procent, sum; let a, b, c;

С помощью знака равно (который еще называют оператором присваивания ) можно присвоить переменной какое-либо значение:

Var income = 300; let price = 76;

Процесс присвоения переменной начального значения называется инициализацией .

Теперь переменная income будет хранить число 300, а переменная price - число 76.

Отличительной чертой переменных является то, что мы можем изменить их значение:

Var income = 300; income = 400; console.log(income); let price = 76; price = 54; console.log(price);

Константы

С помощью ключевого слова const можно определить константу , которая, как и переменная, хранит значение, однако это значение не может быть изменено.

Const rate = 10;

Если мы попробуем изменить ее значение, то мы столкнемся с ошибкой:

Const rate = 10; rate = 23; // ошибка, rate - константа, поэтому мы не можем изменить ее значение

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

Const rate; // ошибка, rate не инициализирована

Переменные и константы в JavaScript. Объявление переменных и присвоение им значений. Переменные глобальные и локальные. Использование констант.

Объявление переменных в JavaScript

Имена переменных в JavaScript могут состоять из букв, цифр, знака $ и знака _, причем имя переменной не может начинаться с цифры. Имейте в виду, что JavaScript чувствителен к регистру букв, и переменные a1 и A1 - это разные переменные. Кириллицу использовать не рекомендуется, хотя это возможно.
Переменные в JavaScript объявляются ключевым словом var:

Var Peremennaya_1 var Peremennaya_2

Использовать переменные в JavaScript без объявления не рекомендуется. Это возможно, но может привести к ошибкам.

Присвоение значения переменным

Присвоение значения объявленным переменным в JavaScript:

Peremennaya_1 = 25 Peremennaya_2 = "Присваиваемый текст заключаем в прямые кавычки"

Можно присваивать значение переменным сразу при объявлении:

Var Peremennaya_1 = 25 var Peremennaya_2 = "Присваиваемый текст заключаем в прямые кавычки"

Значение переменной в JavaScript может изменяться в процессе выполнения программы. При записи в переменную текста, его необходимо заключить в прямые кавычки.

Переменные локальные и глобальные

Если переменная объявлена внутри функции, то она является локальной и будет доступна (иметь видимость) только в пределах этой функции. При выходе из функции локальные переменные в JavaScript уничтожаются, поэтому в разных функциях можно использовать переменные с одним и тем же именем.

Если переменная объявлена вне функций, то она является глобальной и будет доступна (иметь видимость) во всех функциях в пределах страницы. Глобальные переменные уничтожаются в JavaScript при закрытии страницы.

Константы в JavaScript

Константы предназначены для упрощения работы с кодом, когда приходится использовать повторяющиеся значения или выражения. Достаточно однократно задать константе значение и можно сколько угодно его использовать, вставляя в код своих программ. В JavaScript нет ключевого слова для объявления констант, вместо констант используются обычные переменные. Чтобы константы отличались от переменных, их принято обозначать заглавными буквами, при необходимости используя знак подчеркивания:

Var DRUG_CHELOVEKA = "Собака"

Приведенный пример константы не совсем полноценный, так как слово «Собака» и так несложно запомнить и вставлять куда нужно. Использовать константы в JavaScript можно для записи и вставки более сложных значений, например, трудно запоминаемых кодов, наборов символов, длинного текста, веб-адресов, адресов электронной почты, телефонных номеров, различных коэффициентов.

В JavaScript константы можно перезаписывать, как переменные, но если это делать, тогда теряется смысл констант.

I too have had a problem with this. And after quite a while searching for the answer and looking at all the responses by everybody, I think I"ve come up with a viable solution to this.

It seems that most of the answers that I"ve come across is using functions to hold the constants. As many of the users of the MANY forums post about, the functions can be easily over written by users on the client side. I was intrigued by Keith Evetts" answer that the constants object can not be accessed by the outside, but only from the functions on the inside.

So I came up with this solution:

Put everything inside an anonymous function so that way, the variables, objects, etc. cannot be changed by the client side. Also hide the "real" functions by having other functions call the "real" functions from the inside. I also thought of using functions to check if a function has been changed by a user on the client side. If the functions have been changed, change them back using variables that are "protected" on the inside and cannot be changed.

/*Tested in: IE 9.0.8; Firefox 14.0.1; Chrome 20.0.1180.60 m; Not Tested in Safari*/ (function(){ /*The two functions _define and _access are from Keith Evetts 2009 License: LGPL (SETCONST and CONST). They"re the same just as he did them, the only things I changed are the variable names and the text of the error messages. */ //object literal to hold the constants var j = {}; /*Global function _define(String h, mixed m). I named it define to mimic the way PHP "defines" constants. The argument "h" is the name of the const and has to be a string, "m" is the value of the const and has to exist. If there is already a property with the same name in the object holder, then we throw an error. If not, we add the property and set the value to it. This is a "hidden" function and the user doesn"t see any of your coding call this function. You call the _makeDef() in your code and that function calls this function. - You can change the error messages to whatever you want them to say. */ self._define = function(h,m) { if (typeof h !== "string") { throw new Error("I don\"t know what to do."); } if (!m) { throw new Error("I don\"t know what to do."); } else if ((h in j)) { throw new Error("We have a problem!"); } else { j[h] = m; return true; } }; /*Global function _makeDef(String t, mixed y). I named it makeDef because we "make the define" with this function. The argument "t" is the name of the const and doesn"t need to be all caps because I set it to upper case within the function, "y" is the value of the value of the const and has to exist. I make different variables to make it harder for a user to figure out whats going on. We then call the _define function with the two new variables. You call this function in your code to set the constant. You can change the error message to whatever you want it to say. */ self._makeDef = function(t, y) { if(!y) { throw new Error("I don\"t know what to do."); return false; } q = t.toUpperCase(); w = y; _define(q, w); }; /*Global function _getDef(String s). I named it getDef because we "get the define" with this function. The argument "s" is the name of the const and doesn"t need to be all capse because I set it to upper case within the function. I make a different variable to make it harder for a user to figure out whats going on. The function returns the _access function call. I pass the new variable and the original string along to the _access function. I do this because if a user is trying to get the value of something, if there is an error the argument doesn"t get displayed with upper case in the error message. You call this function in your code to get the constant. */ self._getDef = function(s) { z = s.toUpperCase(); return _access(z, s); }; /*Global function _access(String g, String f). I named it access because we "access" the constant through this function. The argument "g" is the name of the const and its all upper case, "f" is also the name of the const, but its the original string that was passed to the _getDef() function. If there is an error, the original string, "f", is displayed. This makes it harder for a user to figure out how the constants are being stored. If there is a property with the same name in the object holder, we return the constant value. If not, we check if the "f" variable exists, if not, set it to the value of "g" and throw an error. This is a "hidden" function and the user doesn"t see any of your coding call this function. You call the _getDef() function in your code and that function calls this function. You can change the error messages to whatever you want them to say. */ self._access = function(g, f) { if (typeof g !== "string") { throw new Error("I don\"t know what to do."); } if (g in j) { return j[g]; } else { if(!f) { f = g; } throw new Error("I don\"t know what to do. I have no idea what \""+f+"\" is."); } }; /*The four variables below are private and cannot be accessed from the outside script except for the functions inside this anonymous function. These variables are strings of the four above functions and will be used by the all-dreaded eval() function to set them back to their original if any of them should be changed by a user trying to hack your code. */ var _define_func_string = "function(h,m) {"+" if (typeof h !== "string") { throw new Error("I don\\"t know what to do."); }"+" if (!m) { throw new Error("I don\\"t know what to do."); }"+" else if ((h in j)) { throw new Error("We have a problem!"); }"+" else {"+" j[h] = m;"+" return true;"+" }"+" }"; var _makeDef_func_string = "function(t, y) {"+" if(!y) { throw new Error("I don\\"t know what to do."); return false; }"+" q = t.toUpperCase();"+" w = y;"+" _define(q, w);"+" }"; var _getDef_func_string = "function(s) {"+" z = s.toUpperCase();"+" return _access(z, s);"+" }"; var _access_func_string = "function(g, f) {"+" if (typeof g !== "string") { throw new Error("I don\\"t know what to do."); }"+" if (g in j) { return j[g]; }"+" else { if(!f) { f = g; } throw new Error("I don\\"t know what to do. I have no idea what \\""+f+"\\" is."); }"+" }"; /*Global function _doFunctionCheck(String u). I named it doFunctionCheck because we"re "checking the functions" The argument "u" is the name of any of the four above function names you want to check. This function will check if a specific line of code is inside a given function. If it is, then we do nothing, if not, then we use the eval() function to set the function back to its original coding using the function string variables above. This function will also throw an error depending upon the doError variable being set to true This is a "hidden" function and the user doesn"t see any of your coding call this function. You call the doCodeCheck() function and that function calls this function. - You can change the error messages to whatever you want them to say. */ self._doFunctionCheck = function(u) { var errMsg = "We have a BIG problem! You\"ve changed my code."; var doError = true; d = u; switch(d.toLowerCase()) { case "_getdef": if(_getDef.toString().indexOf("z = s.toUpperCase();") != -1) { /*do nothing*/ } else { eval("_getDef = "+_getDef_func_string); if(doError === true) { throw new Error(errMsg); } } break; case "_makedef": if(_makeDef.toString().indexOf("q = t.toUpperCase();") != -1) { /*do nothing*/ } else { eval("_makeDef = "+_makeDef_func_string); if(doError === true) { throw new Error(errMsg); } } break; case "_define": if(_define.toString().indexOf("else if((h in j)) {") != -1) { /*do nothing*/ } else { eval("_define = "+_define_func_string); if(doError === true) { throw new Error(errMsg); } } break; case "_access": if(_access.toString().indexOf("else { if(!f) { f = g; }") != -1) { /*do nothing*/ } else { eval("_access = "+_access_func_string); if(doError === true) { throw new Error(errMsg); } } break; default: if(doError === true) { throw new Error("I don\"t know what to do."); } } }; /*Global function _doCodeCheck(String v). I named it doCodeCheck because we"re "doing a code check". The argument "v" is the name of one of the first four functions in this script that you want to check. I make a different variable to make it harder for a user to figure out whats going on. You call this function in your code to check if any of the functions has been changed by the user. */ self._doCodeCheck = function(v) { l = v; _doFunctionCheck(l); }; }())

It also seems that security is really a problem and there is not way to "hide" you programming from the client side. A good idea for me is to compress your code so that it is really hard for anyone, including you, the programmer, to read and understand it. There is a site you can go to: http://javascriptcompressor.com/ . (This is not my site, don"t worry I"m not advertising.) This is a site that will let you compress and obfuscate Javascript code for free.

  1. Copy all the code in the above script and paste it into the top textarea on the javascriptcompressor.com page.
  2. Check the Base62 encode checkbox, check the Shrink Variables checkbox.
  3. Press the Compress button.
  4. Paste and save it all in a .js file and add it to your page in the head of your page.


Понравилась статья? Поделиться с друзьями: