Day 12 JavaScript var vs let (2)

今天介绍 JS 内 var 与 let 的後两点差异。

  1. 执行环境 Execution Context
  2. 宣告 declaration

执行环境 Execution Context:

JS 里最大的执行环境称为全域执行环境 Global Execution Context 。
全域执行环境底下又可分为:

  • Object Environment Records:全域物件环境
    • var 会在此环境下宣告变数,在浏览器中可以用 window 物件执行(在 node.js 可以用 global 执行)。
  • Declarative Environment Records:宣告环境
    • let 会在此环境下宣告变数,无法用 window 或 global 物件执行,因为 window 及 global 是全域物件环境内的物件。

范例

var a = 1;
let b = 2;

console.log(window.a);
//  印出 1
console.log(window.b);
//  印出 undefined

宣告 declaration:

在同作用范围内:

  • var 可以重新宣告。
  • let 无法重新宣告。

范例

var a = 1;
var a = 2;
//  可顺利执行

let b = 3;
let b = 4;
//  印出 "error" SyntaxError: Identifier 'b' has already been declared

参考:
[1]What's the difference between using "let" and "var"?


<<:  Day 12 Component Lifecycle -1

>>:  Day 12 漏洞分析 - Vulnerability Analysis (legion)

Day26 - GitLab CI 启动其它专案启动流水线或动态产出新的流水线,谈触发 trigger

在大型专案中,可能会把专案依功能、架构等等因素,切分为多个子专案,虽然切分为多个子专案,有些逻辑可能...

【Day 27】Design Patterns with Go I:Simple Factory / Factory / Abstract Factory

刚学一点 Go, 除了能够使用别人写好的 modules, 为了程序码的可扩充性,也需要理解 De...

05. Feature Test x HTTP Test x API Test

打开 tests/Feature 让我们来场激烈的 http test 吧! http test 基...

[ 卡卡 DAY 15 ] - React Native 页面导览 Navigation (下)

接下来要在页面上按下按钮跳页 以及按了左边 header icon 回上一页 正所谓有去有回才不会...

小学生学程序设计 Day 27:「夜市的鸡蛋糕」

嘿~~ 各位好,我是菜市场阿龙! 这集要介绍的是「物件导向程序设计」 频道:https://www....