ES6 声明属性
- let(块内变量) var(全局变量)
// let 适合局部变量
for (let i = 0; i < 10; i++) {
let i = 5;
// i 呈现不同的子作用域
}
- 变量作用域,和变量提升(var)
var i;
console.log(i); // undefined
console.log(i); // 先声明i ReferenceError
let i = 2;
- 暂时性死区,重复声明
var i = 1;
if (i) {
i = 2;
let i; // 暂时性死区 ==const 对变量声明赋值失败
}
funtion foo() {
let a = 1;
let b = 2; // error ==const 重复声明error
}
- 块级作用域,const,顶层对象
// 览器环境指的是window对象,在 Node 指的是global对象
var a = 1;
this.a; // 1 Node 模块和 ES6 模块中this返回的是当前模块
window.a; // 1
global.a; // 1
变量解构
let [a,b,c] = [1,2,3];
console.log(a); // 1
let {foo,bar} = {foo:"foo1",bar:"bar1"}
console.log(foo); // foo1
const [a, b, c, d, e] = 'hello';
console.log(a); // h
let {toString: s} = 123;
s === Number.prototype.toString // true
function add([x, y]){
return x + y;
}
add([1, 2]);
函数
var x = 1;
function f(x, y = x) {
console.log(y);
}
f(2) // 2
//
var x = 1;
function foo(x, y = function() { x = 2; }) {
var x = 3;
y();
console.log(x);
}
foo() // 3
x // 1
function add(...values) {
let sum = 0;
for (var val of values) {
sum += val;
}
}
// 严格模式
function doSomething(a, b) {
'use strict';
}
// 默认值、解构赋值、或者扩展运算符 不能使用
// 报错
function doSomething(a, b = a) {
'use strict';
}
var func1 = (num1,num2) => {return num1 + num2}
// this 作用域
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });