JavaScript - Scope of variables
It's important to note, especially if you have come to JavaScript from another language, that variables in JavaScript are not defined in a block scope, but in a function scope. This means that if a variable is defined inside a function, it's not visible outside of the function. However, if it's defined inside an if or a for code block, it's visible outside the block. The term "global variables" describes variables you define outside of any function (in the global program code), as opposed to "local variables", which are defined inside a function. The code inside a function has access to all global variables as well as to its own local ones.
In the next example:
- The f() function has access to the global variable
- Outside the f() function, the local variable doesn't exist
It's also important to note that if you don't use var to declare a variable, this variable is automatically assigned a global scope. Let's see an example:
What happened? The function f() contains the variable local. Before calling the function, the variable doesn't exist. When you call the function for the first time, the variable local is created with a global scope. Then, if you access local outside the function, it will be available.
Best practice tips
Minimize the number of global variables in order to avoid naming collisions. Imagine two people working on two different functions in the same script, and they both decide to use the same name for their global variable. This could easily lead to unexpected results and hard-to-find bugs.
Always declare your variables with the var statement.
Consider a "single var" pattern. Define all variables needed in your function at the very top of the function so you have
a single place to look for variables and hopefully prevent accidental globals.
Variable hoisting
Here's an interesting example that shows an important aspect of local versus global scoping:
var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();
You might expect that the first alert() will display 123 (the value of the global variable a) and the second will display 1 (the local variable a). But, this is not the case. The first alert will show undefined. This is because inside the function the local scope is more important than the global scope. So, a local variable overwrites any global variable with the same name. At the time of the first alert(), the variable a was not yet defined (hence the value undefined), but it still existed in the local space due to the special behavior called hoisting.
When your JavaScript program execution enters a new function, all the variables declared anywhere in the function are moved (or elevated, or hoisted) to the top of the function. This is an important concept to keep in mind. Further, only the declaration is hoisted, meaning only the presence of the variable is moved to the top. Any assignments stay where they are. In the preceding example, the declaration of the local variable a was hoisted to the top. Only the declaration was hoisted, but not the assignment to 1. It's as if the function was written like this:
var a = 123;
function f() {
var a; // same as: var a = undefined;
alert(a); // undefined
a = 1;
alert(a); //
}
You can also adopt the single var pattern mentioned previously in the best practice section. In this case, you'll be doing a sort of manual variable hoisting to prevent confusion with the JavaScript hoisting behavior.
JavaScript - Scope of variables的更多相关文章
- (翻译) How variables are allocated memory in Javascript? | scope chain | lexicial scope
总结: 阅读下面文章需要15分钟 提问者的问题是JavaScript中内存是怎么分配的,在介绍的过程作者涉及计到了JS中 Scope Chain和调用函数call生成lexicial environm ...
- [译] 你该知道的javascript作用域 (javascript scope)(转)
javascript有一些对于初学者甚至是有经验的开发者都难以理解的概念. 这个部分是针对那些听到 : 作用域, 闭包, this, 命名空间, 函数作用域, 函数作用域, 全局作用域, 变量作用域( ...
- [AngularJS] Javascript scope and AngularJS $scope
Scope resolution of our Angular documents works exactly the same way scope resolution works in plain ...
- [CSSinJS] Convert Sass (SCSS) Styled Button to CSSinJS with JavaScript Templates and Variables
This is an introduction to CSSinJS that doesn't require any JavaScript knowledge, just a basic CSS. ...
- javaScript [[scope]]学习笔记
在javaScript 学习中,闭包肯定是一个让人头疼的问题,而闭包必定离不开[[scope]]作用域 scope存储了执行期上下文的集合 而了解scope以及scope链又是一个十分抽象的问题 我们 ...
- JavaScript闭包的底层运行机制
转自:http://blog.leapoahead.com/2015/09/15/js-closure/ 我研究JavaScript闭包(closure)已经有一段时间了.我之前只是学会了如何使用它们 ...
- JavaScript简易教程(转)
原文:http://www.cnblogs.com/yanhaijing/p/3685304.html 这是我所知道的最完整最简洁的JavaScript基础教程. 这篇文章带你尽快走进JavaScri ...
- JAVASCRIPT的一些知识点梳理
春节闲点,可以安心的梳理一下以前不是很清楚的东东.. 看的是以下几个URL: http://web.jobbole.com/82520/ http://blog.csdn.net/luoweifu/a ...
- 【JS】Intermediate5:Scope
1.Scope=variable visibility a variable’s scope is the part of your code that can access and modify t ...
随机推荐
- Week2-作业1:阅读与博客
Week2-作业1:阅读与博客 第一章 :概论 1. 原文如下: 移山公司程序员阿超的宝贝儿子上了小学二年级,老师让家长每天出30道加减法题目给孩子做.阿超想写一个小程序来做这件事,具体实现可以采用很 ...
- 简单实现wc.exe软件基本功能
简单实现wc.exe软件基本功能 软件需求分析: 一.基本功能 支持 -c 统计字符数(char count) 支持 -w 统计单词数(word count) 支持 -l 统计总行数(line ...
- Gradle入门(2):构建简介
基本概念 在Gradle中,有两个基本概念:项目和任务.请看以下详解: 项目是指我们的构建产物(比如Jar包)或实施产物(将应用程序部署到生产环境).一个项目包含一个或多个任务. 任务是指不可分的最小 ...
- UVA10917_Walk Through the Forest
无向图.对于两个相连的点,如果A到终点的最短路径大于B到终点的最短路径,那么A可以往B走,求最终从起点到终点有多少种走法? 首先我们可以直接预处理所有点到终点的最短路径.然后分别判断所有的边两点是否满 ...
- UVALive6443_Alien Abduction Again
题意为给你若干个三次函数,以及每一个函数所分布的区间,由于每个函数的所有的系数都是整数,所以最后的函数在整数点处的值也是整数. 现在每次可以插入函数或者询问区间,现在要求每次询问区间后,所有的函数在这 ...
- Mxnet Windows配置
MXNET Windows 编译安装(Python) 本文只记录Mxnet在windows下的编译安装,更多环境配置请移步官方文档:http://mxnet.readthedocs.io/en/lat ...
- 超计算(Hyper computation)模型
超计算(Hyper computation)模型 作者:Xyan Xcllet链接:https://www.zhihu.com/question/21579465/answer/106995708来源 ...
- huhamhire-hosts — Hosts文件自动配置工具
https://www.anotherhome.net/1376 推荐配合EasyGoAgent使用: EasyGoAgent — 开箱即用的GoAgent Update 2015.5.15 数据文件 ...
- Docker Machine 和 Docker Engine 的区别
Docker Engine 当人们提到 Docker,一般而言,大家说的是 Docker Engine,如下图: 它是一个 client-server application. Docker Eng ...
- BZOJ4727 [POI2017]Turysta 【竞赛图哈密顿路径/回路】
题目链接 BZOJ4727 题解 前置芝士 1.竞赛图存在哈密顿路径 2.竞赛图存在哈密顿回路,当且仅当它是强联通的 所以我们将图缩点后,拓扑排序后一定是一条链,且之前的块内的点和之后块内的点的边一定 ...