ES6 块级作用域

ES6 块级作用域

var 变量提升

  • 全局作用域下自动转换为window对象属性,而let、const不会。
function test1() {
  console.log(a) // undefined
  if(false) {
    var a = 1;
  }
  console.log(a) // undefined
  function inner() {
    if(false) {
      var b = 2
    }
  }
  console.log(b); //RefrenceError b is not defined
}

示例:http://jsbin.com/tunonipare/edit?html,js,console

let 块级作用域

  • 可以读取外层变量、可以重新定义外层变量,但是不能在块级作用域内重新声明函数如果必须要使用函数表达式声明。块级作用域声明函数必须在大括号内。
function test() {
  let a = 1;
  if(true) {
    let b = 2;
  }
  console.log(a); // 1
  console.log(b); // b is not defined
}
test();

for(var i = 0; i < 5; i++) {
  setTimeout(() => {
    console.log(`1: ${i}`); // 5 5 5 5 5
  }, 0);
  
  (function(i) {
    setTimeout(() => {
      console.log(`2: ${i}`) // 0 1 2 3 4
    }, 0);
  })(i);
}
console.log(i);

for(let j = 0; j< 5; j++) {
  setTimeout(() => {
    console.log(`3: ${j}`) // 0 1 2 3 4
  }, 0);
}
console.log(j); // j is not defined

示例:http://jsbin.com/tatahor/28/edit?js,console

  • 暂时性死区:只要块级作用域内有let命令,它声明的变量就绑定了该区域,不受外部变量影响。
var tmp = [];
var obj = {a: 1};
if(false) {
    obj.b = 2;
    typeof obj; // undefined;
    tmp = 1; // RefrenceError: tmp is not defined;
    typeof tmp; // RefrenceError: tmp is not defined;
    let tmp = 1;
}
console.log(tmp) // []
console.log(obj) // {a: 1, b: 2};

function(a = b, b = 1) { // RefrenceError: b is not defined
    console.log(a + b);
}
function(a = 1, b = a) { // success
    console.log(a + b);
}

示例:http://jsbin.com/qazarod/14/edit?js,console

const 常量

  • 常量必须初始化赋值,不可更改。
const type = "ACTION";
type = 1; // error
console.log(type);

const obj = {
  a: 1,
  b: 2
}
obj.a = 2;
delete obj.b
console.log(obj); // {a: 2}

示例:http://jsbin.com/coxudin/4/edit?js,console

最佳实践

  • 默认使用const,只有需要改变时才用let防止变量被错误修改。

转载请注明出处

Read more

Flutter入门指南

Flutter入门指南

Flutter 是一个由 Google 开发的开源移动应用开发框架。它允许开发者使用一套代码同时构建 iOS 和 Android 应用,并且提供了丰富的 UI 组件和高效的开发工具,使得开发者能够快速构建出高性能的跨平台应用。 一、Flutter 的实现原理 Flutter 的核心在于其自带的高性能渲染引擎 Skia。不同于其他框架依赖于原生的 UI 组件,Flutter 直接通过 Skia 渲染引擎将所有组件绘制到屏幕上。这种方式保证了跨平台应用在 iOS 和 Android 上的表现完全一致。 1.1 结构概览 Flutter 的架构分为三层: 1. Framework(框架层): 这部分主要由 Dart 编写,提供了 Flutter 的各种 UI 组件(Widget)、手势检测、渲染层以及动画等。

By Lewis
Certbot Let's Encrypt 证书自动续期

Certbot Let's Encrypt 证书自动续期

安装 Certbot yum install epel-release -y yum install certbot -y certbot certonly //生成证书 certbot renew //续期 certbot certificates //查看证书 域名验证插件 https://github.com/ywdblog/certbot-letencrypt-wildcardcertificates-alydns-au 下载 $ git clone https://github.com/ywdblog/certbot-letencrypt-wildcardcertificates-alydns-au $ cd certbot-letencrypt-wildcardcertificates-alydns-au $ chmod 0777 au.sh 配置 DNS API 密钥: 这个 API 密钥什么意思呢?由于需要通过 API 操作阿里云 DNS,

By Lewis