Home  >  Article  >  Web Front-end  >  Introducing JavaScript variable scope examples

Introducing JavaScript variable scope examples

零下一度
零下一度Original
2017-06-28 13:47:211240browse

This article mainly introduces JavaScript variable scope. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.

In JavaScript, variables declared with var actually have scope.

If a variable is declared inside the function body, the scope of the variable is the entire function body, and the variable cannot be referenced outside the function body:


'use strict';

function foo() {
  var x = 1;
  x = x + 1;
}

x = x + 2; // ReferenceError! 无法在函数体外引用变量x

If two different functions declare the same variable, the variable will only work within the respective function bodies. In other words, variables with the same name inside different functions are independent of each other and do not affect each other:


'use strict';

function foo() {
  var x = 1;
  x = x + 1;
}

function bar() {
  var x = 'A';
  x = x + 'B';
}

Since JavaScript functions can be nested, at this time, Internal functions can access variables defined by external functions, but not vice versa:


'use strict';

function foo() {
  var x = 1;
  function bar() {
    var y = x + 1; // bar可以访问foo的变量x!
  }
  var z = y + 1; // ReferenceError! foo不可以访问bar的变量y!
}

What to do if the variable names of internal functions and external functions have the same name ?


'use strict';

function foo() {
  var x = 1;
  function bar() {
    var x = 'A';
    alert('x in bar() = ' + x); // 'A'
  }
  alert('x in foo() = ' + x); // 1
  bar();
}

This shows that when searching for variables, JavaScript functions start from their own function definitions and search from "inside" to "outside". If the internal function defines a variable with the same name as the external function, the variables of the internal function will "shield" the variables of the external function.

Variable promotion

JavaScript function definition has a special feature. It will first scan the entire function body statement and "promote" all declared variables to Top of the function:


'use strict';

function foo() {
  var x = 'Hello, ' + y;
  alert(x);
  var y = 'Bob';
}

foo();

Although it is in strict mode, the statement var x = 'Hello, ' + y; does not report an error, the reason It is the variable y that is declared later. But alert displays Hello, undefined, indicating that the value of variable y is undefined. This is precisely because the JavaScript engine automatically elevates the declaration of variable y, but does not elevate the assignment of variable y.

For the above foo() function, the code seen by the JavaScript engine is equivalent to:


function foo() {
  var y; // 提升变量y的申明
  var x = 'Hello, ' + y;
  alert(x);
  y = 'Bob';
}

Due to this weird "feature" of JavaScript, when we define variables inside a function, please strictly abide by the rule of "declare all variables inside the function first". The most common approach is to use a var to declare all variables used inside the function:


function foo() {
  var
    x = 1, // x初始化为1
    y = x + 1, // y初始化为2
    z, i; // z和i为undefined
  // 其他语句:
  for (i=0; i<100; i++) {
    ...
  }
}

Global scope

Variables that are not defined within any function have global scope. In fact, JavaScript has a global object window by default, and variables in the global scope are actually bound to a property of window:


&#39;use strict&#39;;

var course = &#39;Learn JavaScript&#39;;
alert(course); // &#39;Learn JavaScript&#39;
alert(window.course); // &#39;Learn JavaScript&#39;

Therefore, directly accessing the global variable course is exactly the same as accessing window.course.

You may have guessed that since there are two ways to define a function, the function defined in variable way var foo = function () {} is actually a global variable, so , the definition of the top-level function is also treated as a global variable and bound to the window object:


&#39;use strict&#39;;

function foo() {
  alert(&#39;foo&#39;);
}

foo(); // 直接调用foo()
window.foo(); // 通过window.foo()调用

Further bold guess, The alert() function we call directly every time is actually a variable of window:


&#39;use strict&#39;;

window.alert(&#39;调用window.alert()&#39;);
// 把alert保存到另一个变量:
var old_alert = window.alert;
// 给alert赋一个新函数:
window.alert = function () {}

// 恢复alert:
window.alert = old_alert;
alert(&#39;又可以用alert()了!&#39;);

This shows that JavaScript actually has only one global scope. If any variable (function is also regarded as a variable) is not found in the current function scope, it will continue to search upwards. Finally, if it is not found in the global scope, a ReferenceError will be reported.

Namespace

Global variables will be bound to window. If different JavaScript files use the same Global variables, or top-level functions defined with the same name, can cause naming conflicts that are difficult to detect.

One way to reduce conflicts is to bind all your variables and functions to a global variable. For example:


// 唯一的全局变量MYAPP:
var MYAPP = {};

// 其他变量:
MYAPP.name = &#39;myapp&#39;;
MYAPP.version = 1.0;

// 其他函数:
MYAPP.foo = function () {
  return &#39;foo&#39;;
};

Put all your code into the unique name space MYAPP, which will greatly reduce the possibility of global variable conflicts.

Many famous JavaScript libraries do this: jQuery, YUI, underscore, etc.

Local scope

Since JavaScript’s variable scope is actually inside the function, we wait in the for loop Variables with local scope cannot be defined in statement blocks:


&#39;use strict&#39;;

function foo() {
  for (var i=0; i<100; i++) {
    //
  }
  i += 100; // 仍然可以引用变量i
}

In order to solve the block-level scope, ES6 introduced the new keyword let, using Let can declare a block-scope variable instead of var:


&#39;use strict&#39;;

function foo() {
  var sum = 0;
  for (let i=0; i<100; i++) {
    sum += i;
  }
  i += 1; // SyntaxError
}

Constant

由于varlet申明的是变量,如果要申明一个常量,在ES6之前是不行的,我们通常用全部大写的变量来表示“这是一个常量,不要修改它的值”:


var PI = 3.14;

ES6标准引入了新的关键字const来定义常量,const与let都具有块级作用域:


&#39;use strict&#39;;

const PI = 3.14;
PI = 3; // 某些浏览器不报错,但是无效果!
PI; // 3.14

The above is the detailed content of Introducing JavaScript variable scope examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn