javascript中的变量作用域以及变量提升详细介绍


Posted in Javascript onOctober 24, 2013

变量作用域
“一个变量的作用域表示这个变量存在的上下文。它指定了你可以访问哪些变量以及你是否有权限访问某个变量。”

变量作用域分为局部作用域和全局作用域。

局部变量(处于函数级别的作用域)
不像其他对面对象的编程语言(比方说C++,Java等等),javascript没有块级作用域(被花括号包围的);当是,javascript有拥有函数级别的作用域,也就是说,在一个函数内定义的变量只能在函数内部访问或者这个函数内部的函数访问(闭包除外,这个我们过几天再写个专题)。

函数级别作用域的一个例子:

var name = "Richard";function showName () {
    var name = "Jack"; // local variable; only accessible in this showName function
    console.log (name); // Jack
}
console.log (name); // Richard: the global variable

没有块级作用域:

var name = "Richard";
// the blocks in this if statement do not create a local context for the name variable
if (name) {
    name = "Jack"; // this name is the global name variable and it is being changed to "Jack" here
    console.log (name); // Jack: still the global variable
}// Here, the name variable is the same global name variable, but it was changed in the if statement
console.log (name); // Jack

//    不要忘记使用var关键字
//    如果声明一个变量的时候没有使用var关键字,那么这个变量将是一个全局变量!
// If you don't declare your local variables with the var keyword, they are part of the global scope
var name = "Michael Jackson";
function showCelebrityName () {
    console.log (name);
}
function showOrdinaryPersonName () {    
    name = "Johnny Evers";
    console.log (name);
}
showCelebrityName (); // Michael Jackson
// name is not a local variable, it simply changes the global name variable
showOrdinaryPersonName (); // Johnny Evers
// The global variable is now Johnny Evers, not the celebrity name anymore
showCelebrityName (); // Johnny Evers
// The solution is to declare your local variable with the var keyword
function showOrdinaryPersonName () {    
    var name = "Johnny Evers"; // Now name is always a local variable and it will not overwrite the global variable
    console.log (name);
}
//    局部变量优先级大于全局变量
//如果在全局作用域中什么的变量在局部作用域中再次声明,那么在局部作用域中调用这个变量时,优先调用局部作用域中声明的变量: 
var name = "Paul";
function users () {
    // Here, the name variable is local and it takes precedence over the same name variable in the global scope
var name = "Jack";
// The search for name starts right here inside the function before it attempts to look outside the function in the global scope
console.log (name); 
}
users (); // Jack

全局变量
所有在函数外面声明的变量都处于全局作用域中。在浏览器环境中,这个全局作用域就是我们的Window对象(或者整个HTML文档)。

每一个在函数外部声明或者定义的变量都是一个全局对象,所以这个变量可以在任何地方被使用,例如:

// name and sex is not in any function
var myName = "zhou";
var sex = "male";//他们都处在window对象中
console.log(window.myName); //paul
console.log('sex' in window); //true

如果一个变量第一次初始化/声明的时候没有使用var关键字,那么他自动加入到全局作用域中。
function showAge(){
  //age初始化时没有使用var关键字,所以它是一个全局变量
  age = 20;
  console.log(age);
}showAge();  //20
console.log(age); //因为age是全局变量,所以这里输出的也是20

setTimeout中的函数是在全局作用域中执行的

setTimeout中的函数所处在于全局作用域中,所以函数中使用this关键字时,这个this关键字指向的是全局对象(Window):

var Value1 = 200;
var Value2 = 20;
var myObj = {
  Value1 : 10,
  Value2 : 1,  caleculatedIt: function(){
    setTimeout(function(){
      console.log(this.Value1 * this.Value2);
    }, 1000);
  }
}
myObj.caleculatedIt(); //4000

为了避免对全局作用域的污染, 所以一般情况下我们尽可能少的声明全局变量。 
变量提升(Variable Hoisting)
所以的变量声明都会提升到函数的开头(如果这个变量在这个函数里面)或者全局作用域的开头(如果这个变量是一个全局变量)。我们来看一个例子:

function showName () {
console.log ("First Name: " + name);
var name = "Ford";
console.log ("Last Name: " + name);
}showName (); 
// First Name: undefined
// Last Name: Ford
// The reason undefined prints first is because the local variable name was hoisted to the top of the function
// Which means it is this local variable that get calls the first time.
// This is how the code is actually processed by the JavaScript engine:
function showName () {
    var name; // name is hoisted (note that is undefined at this point, since the assignment happens below)
console.log ("First Name: " + name); // First Name: undefined
name = "Ford"; // name is assigned a value
// now name is Ford
console.log ("Last Name: " + name); // Last Name: Ford
}

函数声明会覆盖变量声明
如果存在函数声明和变量声明(注意:仅仅是声明,还没有被赋值),而且变量名跟函数名是相同的,那么,它们都会被提示到外部作用域的开头,但是,函数的优先级更高,所以变量的值会被函数覆盖掉。

// Both the variable and the function are named myName
var myName;?
function myName () {
console.log ("Rich");
}// The function declaration overrides the variable name
console.log(typeof myName); // function

但是,如果这个变量或者函数其中是赋值了的,那么另外一个将无法覆盖它:

// But in this example, the variable assignment overrides the function declaration
var myName = "Richard"; // This is the variable assignment (initialization) that overrides the function declaration.function myName () {
console.log ("Rich");
}
console.log(typeof myName); // string

最后一点, 在严格模式下,如果没有先声明变量就给变量赋值将会报错!

Javascript 相关文章推荐
js宝典学习笔记(上)
Jan 10 Javascript
斜45度寻路实现函数
Aug 20 Javascript
js相册效果代码(点击创建即可)
Apr 16 Javascript
javascript 面向对象封装与继承
Nov 27 Javascript
javascript+canvas制作九宫格小程序
Dec 28 Javascript
JQuery中DOM事件绑定用法详解
Jun 13 Javascript
javascript制作幻灯片(360度全景图片)
Jul 28 Javascript
在AngularJS中使用jQuery的zTree插件的方法
Apr 21 Javascript
微信小程序 swiper组件轮播图详解及实例
Nov 16 Javascript
AngularJS实现给动态生成的元素绑定事件的方法
Dec 14 Javascript
node.js 发布订阅模式的实例
Sep 10 Javascript
Jquery+javascript实现支付网页数字键盘
Dec 21 jQuery
sencha touch 模仿tabpanel导航栏TabBar的实例代码
Oct 24 #Javascript
jQuery设置div一直在页面顶部显示的方法
Oct 24 #Javascript
JS+CSS设置img在DIV中只显示Img垂直居中的部分
Oct 24 #Javascript
JS 获取滚动条高度示例代码
Oct 24 #Javascript
通过javascript把图片转化为字符画
Oct 24 #Javascript
js编写trim()函数及正则表达式的运用
Oct 24 #Javascript
原生JS实现加入收藏夹的代码
Oct 24 #Javascript
You might like
PHP乱码问题,UTF-8乱码常见问题小结
2012/04/09 PHP
CURL状态码列表(详细)
2013/06/27 PHP
php生成随机颜色方法汇总
2014/12/03 PHP
thinkphp3.2嵌入百度编辑器ueditor的实例代码
2017/07/13 PHP
Thinkphp框架使用list_to_tree 实现无限级分类列出所有节点示例
2020/04/04 PHP
推荐一些非常不错的javascript学习资源站点
2007/08/29 Javascript
javascript显示隐藏层比较不错的方法分析
2008/09/30 Javascript
Javascript 对象的解释
2008/11/24 Javascript
js实现addClass,removeClass,hasClass的函数代码
2011/07/13 Javascript
JavaScript Math.floor方法(对数值向下取整)
2015/01/09 Javascript
6种javascript显示当前系统时间代码
2015/12/01 Javascript
解决JS组件bootstrap table分页实现过程中遇到的问题
2016/04/21 Javascript
JavaScript代码性能优化总结(推荐)
2016/05/16 Javascript
30分钟快速掌握Bootstrap框架
2016/05/24 Javascript
a标签置灰不可点击的实现方法
2017/02/06 Javascript
vue2 前后端分离项目ajax跨域session问题解决方法
2017/04/27 Javascript
js图片放大镜实例讲解(必看篇)
2017/07/17 Javascript
JS实现留言板功能[楼层效果展示]
2017/12/27 Javascript
详解vue表单——小白速看
2018/04/08 Javascript
Angular6使用forRoot() 注册单一实例服务问题
2019/08/27 Javascript
js实现经典贪吃蛇小游戏
2020/03/19 Javascript
使用Python监控文件内容变化代码实例
2018/06/04 Python
tensorflow实现逻辑回归模型
2018/09/08 Python
Python音频操作工具PyAudio上手教程详解
2019/06/26 Python
Python批量启动多线程代码实例
2020/02/18 Python
python图形界面开发之wxPython树控件使用方法详解
2020/02/24 Python
通过HTML5 Canvas API绘制弧线和圆形的教程
2016/03/14 HTML / CSS
Jabra捷波朗美国官网:用于办公、车载和运动的无线蓝牙耳麦
2017/02/01 全球购物
千禧酒店及度假村官方网站:Millennium Hotels and Resorts
2019/05/10 全球购物
英国景点门票网站:attractiontix
2019/08/27 全球购物
带薪年假请假条
2014/02/04 职场文书
班组长岗位职责
2014/03/03 职场文书
学生会竞选演讲稿
2014/04/24 职场文书
2015年乡镇人大工作总结
2015/04/22 职场文书
工作违纪的检讨书范文
2019/07/09 职场文书
节约用水广告语60条
2019/11/14 职场文书