if
and while
). var a = 10; function app(){ var b = 2; console.log(a); // 10 console.log(b); // 2 } console.log(b); // ReferenceError: b is not defined app();
app
function. Outside the local scope, we do not have access to a local variable. var a = 10; function app(){ var b = 2; var d = 3; function add(){ var c = a + b; } return add; } var x = app(); console.dir(x);
app
is the parent function, add
is the child function.app
function, which then returns the add
function. This allows you to see all the properties of the add
function object.Closure
object inside the Scopes
data array.add
has access to the variables b and d that belong to the external function, these two variables will be added to the Closure
object as a reference. var a = 10; var startFunc; function app(){ var b = 2; function add(){ var c = a + b; console.log(c); } startFunc = add(); } app(); // Invoke the app function startFunc; // as the app function invoked above will assign the add function to startFunc & console the value of c
startFunc
function startFunc
assigned the function add
, which is a child of the parent app
function.startFunc
function will behave as a global variable without an assigned value. (function(){ //variables & scope that inside the function })();
var studnetEnrollment = (function () { //private variables which no one can change //except the function declared below. var count = 0; var prefix = "S"; // returning a named function expression function innerFunc() { count = count + 1; return prefix + count; }; return innerFunc; })(); var x = studnetEnrollment(); // S1 console.log(x); var y = studnetEnrollment(); // S2 console.log(y);
count
and prefix
are two private variables that cannot be changed. Access to them is open only for the inner function (in our case, this is the innerFunc
function).studentEnrollment
function is called, the studentEnrollment
function increases the value of the count
variable to 1.count
value increases from 1 to 2.Source: https://habr.com/ru/post/450988/
All Articles