February 26, 2024

let、const和var

let

let x; //正确用法
let y = 5;
y = 6; //正确用法

const

const x; //用法错误,const必须在声明时定义  
const x = 4; //用法正确

const y = 5;
y = 6; //错误用法

const numbers = [1, 2, 3];
numbers.push(4); // 正确
numbers = [1, 2, 3, 4]; // 抛出错误

const foo = new Foo('rob'); //正确
foo.say_name(); // 正确
foo = new Foo2(); // 抛出错误

var

前两个都是块级作用域,var则是全局作用域,容易混淆。

About this Post

This post is written by void2eye, licensed under CC BY-NC 4.0.

#Web