个性化阅读
专注于IT技术分析

javascript中变量声明中LET和VAR有什么区别

点击下载

var和let是简单的声明符, 允许在作用域中声明变量。

让我们的工作非常像var。主要区别在于var变量的范围是整个封闭函数。

但是, 这到底意味着什么?例如 :

假设我们有10个具有10个不同id的按钮, 但它们都遵循前缀” thebutton”。

// Using VAR
for(var i=1; i<10; i++) {
    $("#thebutton" + i).click(function () { 
          alert(i); 
    });
}

变量i将在按钮的单击功能范围内作为i的参考。这意味着, 如果你单击任何按钮, 该值将始终为10。

'use strict'; 
// We need to set use strict, because all the Block-scoped declarations (let, const, function, class) are not yet supported outside strict mode

// Using let
for(let i=1; i<10; i++) {
    $("#thebutton" + i).click(function () { 
          alert(i); 
    });
}

玩这个例子:

历史是另一回事!由于let指令, 每个按钮都会连续提醒其编号。

真的很简单不是吗? let将仅在其块范围内应用!

{ 
// Start block

// let will be useful here !

// End Block
}

如果你还不了解, 请尝试另一个示例:

'use strict';

var country = "russia";
var a = 5;
var b = 10;

if (country === "russia") {
  let a = 50; // A will be 50 only in russia !
  var b = 1; // Will be applied globally, B will be change in all the world !

  console.log(a);  // 50
  console.log(b);  // 1
}

// We are outside russia !!!

console.log(a); // a will be 5 again !
console.log(b); // 1

希望本文对理解这两个语句之间的区别有所帮助。

赞(0)
未经允许不得转载:srcmini » javascript中变量声明中LET和VAR有什么区别

评论 抢沙发

评论前必须登录!