What's the difference between using “let” and “var” to declare a variable in JavaScript?
答案1
The difference is scoping. var is scoped to the nearest function block and let is scoped to the nearest enclosing block, which can be smaller than a function block. Both are global if outside any block.
Also, variables declared with let are not accessible before they are declared in their enclosing block. As seen in the demo, this will throw a ReferenceError exception.
var html = '';
write('#### global ####\n');
write('globalVar: ' + globalVar); //undefined, but visible
try {
write('globalLet: ' + globalLet); //undefined, *not* visible
} catch (exception) {
write('globalLet: exception');
}
write('\nset variables');
var globalVar = 'globalVar';
let globalLet = 'globalLet';
write('\nglobalVar: ' + globalVar);
write('globalLet: ' + globalLet);
function functionScoped() {
write('\n#### function ####');
write('\nfunctionVar: ' + functionVar); //undefined, but visible
try {
write('functionLet: ' + functionLet); //undefined, *not* visible
} catch (exception) {
write('functionLet: exception');
}
write('\nset variables');
var functionVar = 'functionVar';
let functionLet = 'functionLet';
write('\nfunctionVar: ' + functionVar);
write('functionLet: ' + functionLet);
}
function blockScoped() {
write('\n#### block ####');
write('\nblockVar: ' + blockVar); //undefined, but visible
try {
write('blockLet: ' + blockLet); //undefined, *not* visible
} catch (exception) {
write('blockLet: exception');
}
for (var blockVar = 'blockVar', blockIndex = 0; blockIndex < 1; blockIndex++) {
write('\nblockVar: ' + blockVar); // visible here and whole function
};
for (let blockLet = 'blockLet', letIndex = 0; letIndex < 1; letIndex++) {
write('blockLet: ' + blockLet); // visible only here
};
write('\nblockVar: ' + blockVar);
try {
write('blockLet: ' + blockLet); //undefined, *not* visible
} catch (exception) {
write('blockLet: exception');
}
}
function write(line) {
html += (line ? line : '') + '<br />';
}
functionScoped();
blockScoped();
document.getElementById('results').innerHTML = html;
Global:
They are very similar when used like this outside a function block.
let me = 'go'; // globally scoped
var i = 'able'; // globally scoped
However, global variables defined with let will not be added as properties on the global windowobject like those defined with var.
console.log(window.me); // undefined
console.log(window.i); // 'able'
Function:
They are identical when used like this in a function block.
function ingWithinEstablishedParameters() {
let terOfRecommendation = 'awesome worker!'; //function block scoped
var sityCheerleading = 'go!'; //function block scoped
}
Block:
Here is the difference. let is only visible in the for() loop and var is visible to the whole function.
unction allyIlliterate() {
//tuce is *not* visible out here
for( let tuce = 0; tuce < 5; tuce++ ) {
//tuce is only visible in here (and in the for() parentheses)
//and there is a separate tuce variable for each iteration of the loop
}
//tuce is *not* visible out here
}
function byE40() {
//nish *is* visible out here
for( var nish = 0; nish < 5; nish++ ) {
//nish is visible to the whole function
}
//nish *is* visible out here
}
Redeclaration:
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not:
'use strict';
let me = 'foo';
let me = 'bar'; // SyntaxError: Identifier 'me' has already been declared
'use strict';
var me = 'foo';
var me = 'bar'; // No problem, `me` is replaced.
答案2
let can also be used to avoid problems with closures. It binds fresh value rather than keeping an old reference as shown in examples below.
for(var i = 1; i < 6; i++) {
document.getElementById('my-element' + i)
.addEventListener('click', function() { alert(i) })
}
Code above demonstrates a classic JavaScript closure problem. Reference to the i variable is being stored in the click handler closure, rather than the actual value of i.
Every single click handler will refer to the same object because there’s only one counter object which holds 6 so you get six on each click.
General workaround is to wrap this in an anonymous function and pass i as argument. Such issues can also be avoided now by using let instead var as shown in code below.
'use strict';
for(let i = 1; i < 6; i++) {
document.getElementById('my-element' + i)
.addEventListener('click', function() { alert(i) })
}
What's the difference between using “let” and “var” to declare a variable in JavaScript?的更多相关文章
- Javascript——概述 && 继承 && 复用 && 私有成员 && 构造函数
原文链接:A re-introduction to JavaScript (JS tutorial) Why a re-introduction? Because JavaScript is noto ...
- JavaScript var, let, const difference All In One
JavaScript var, let, const difference All In One js var, let, const 区别 All In One 是否存在 hoisting var ...
- 【译】PHP的变量实现(给PHP开发者的PHP源码-第三部分)
文章来自:http://www.aintnot.com/2016/02/12/phps-source-code-for-php-developers-part3-variables-ch 原文:htt ...
- Expression Tree Basics 表达式树原理
variable point to code variable expression tree data structure lamda expression anonymous function 原 ...
- Groovy 模版引擎
1. Introduction Groovy supports multiple ways to generate text dynamically including GStrings, print ...
- js 日期按年月日加减
<script> function isleapyear(year) { if(parseInt(year)%4==0 && parseInt(year)%100!=0)r ...
- coffeescript 1.8.0 documents
CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque ...
- JavaScript闭包的底层运行机制
转自:http://blog.leapoahead.com/2015/09/15/js-closure/ 我研究JavaScript闭包(closure)已经有一段时间了.我之前只是学会了如何使用它们 ...
- SAS Annotated Output GLM
SAS Annotated Output GLM 在使用SAS过程中,proc glm步输出离差平方和有4种算法,分别是SS1 SS2 SS3 SS4 下面文章介绍了其中SS3的具体计算步骤和例子 ...
随机推荐
- mysql小知识点汇总
附录:(更新于2013-11-21) sql必知必会学习笔记:http://www.cnblogs.com/IPrograming/category/509859.html mysql 基本命令学习: ...
- Python 基础函数
函数: 在程序设计中,函数是指用于进行某种计算的一系列语句的有名称的组合. 定义一个函数时,需要指定函数的名称并写下一系列程序语句.定义时不会执行,运行代码时,先加载进内存中,之后使用名称来调用这个函 ...
- 【BZOJ2286】[Sdoi2011]消耗战 虚树
[BZOJ2286][Sdoi2011]消耗战 Description 在一场战争中,战场由n个岛屿和n-1个桥梁组成,保证每两个岛屿间有且仅有一条路径可达.现在,我军已经侦查到敌军的总部在编号为1的 ...
- KVC && KVO 初见
Look,这是一个很简单的要求,点击Add me,age +1. 想一想的话很简单的,设置一个属性Nsinteger age,点击button add me,直接加1在重新显示Lable就好啦,不过, ...
- CRM客户关系管理系统-需求概设和详设
大概设计 大概设计就是对需求进行一个整体性分析,把需要实现的功能都列出来,对于客户关系管理系统,我们需要从角色出发,从而确定有哪些需求,最好是画个思维导图 首先我们是为培训学校这么一个场景来开发的,所 ...
- Redis作者谈Redis应用场景(转)
add by zhj : 这是Redis的作者antirez在他的技术博客中写的一篇文章 英文原文:take-advantage-of-redis-adding-it-to-your-stack 译文 ...
- python多进程编程(二)
进程同步(锁) 进程之间数据不共享,但是共享同一套文件系统,所以访问同一个文件,或同一个打印终端,是没有问题的, 而共享带来的是竞争,竞争带来的结果就是错乱,如何控制,就是加锁处理 part1:多个进 ...
- 给俺的 CSDN 博客加背景音乐 - 高大尚的《心经》背景音乐
给俺的 CSDN 博客加背景音乐 - 高大尚的<心经>背景音乐 太阳火神的漂亮人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途- ...
- JS单例
s = (function S(){ var bean; function get(){ if(bean){ return bean }else{ bean = T(); return bean; } ...
- Selenium获取input输入框中值的几种方法
1.selenium 自带的方法 get_attribute('value') driver.find_element_by_name("f[url]").get_attribut ...