let const
1.let,const 不能重复声明:可以用来检测重复命名,没有变量提升
ex:
console.log(a)
let a;
//Uncaught ReferenceError: a is not defined
let a;
let a;
//Uncaught SyntaxError: Identifier 'a' has already been declared
2.块级作用域
let、const声明的变量只在块级作用域中起作用。
{
let a;
}
console.log(a)
//test.html:20 Uncaught ReferenceError: a is not defined
3.暂时性死区
块级作用域内一旦用let、const声明了变量,只会在块级作用域中使用该变量,不会再全局中查找该变量。
let a = 1;
{
console.log(a);
let a;
}
//Uncaught ReferenceError: a is not defined
4.const 声明必须初始化,不能重复赋值
const a;
//Uncaught SyntaxError: Missing initializer in const declaration
5.const :声明的是常量,不能改变的其实是地址
/ 1.基本数据类型不能修改值
const a = 10;
a = 20;
//test.html:32 Uncaught TypeError: Assignment to constant variable.
//2. 引用类型可以修改值,但是不能修改地址
const arr = [];
arr[0] = 1;
console.log(arr);//[1]
arr = [];//Uncaught TypeError: Assignment to constant variable.
箭头函数
语法:()=>{}
// 如果只有一个参数的情况,可以省略();
const a = (i)=>{
console.log(i)
}
const a = i=>{
console.log(i)
}
//如果只有一行语句,并且返回值就是这行语句的结果,可以省略return和{};
const b = (a,b)=>{
return a+b
}
const b = (a,b)=>a+b;
//箭头函数体的闭包( i=0 是默认参数)
var Add = (i=0) => {return (() => (++i) )};
var v = Add();
v(); //1
v(); //2
var add = (i=0)=>()=>(++i)
function a1(x){
x == 0? 1:x*a(x-1)
}
const a = (x)=>{
return x == 0? 1:x*a(x-1);
}
console.log(a(5))
//递归
var fact = (x) => ( x==0 ? 1 : x*fact(x-1) );
fact(5); // 120
this指向
//this始终指向它被创建时所处的函数上下文中的this。
//箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this
var str = 'window';
const obj = {
str:'obj',
f1: function(){
console.log(this.str, '当前作用域中的this');
return function(){
console.log('原生函数',this.str);
}
},
f2: function(){
console.log(this.str, '当前作用域中的this');
return ()=>{
console.log('箭头函数',this.str);
}
}
};
const obj2 = {
str:'obj2'
}
var nativeFn = obj.f1();//obj 当前作用域中的this
var arrowFn = obj.f2();//obj 当前作用域中的this
nativeFn();//原生函数 window
arrowFn(); //箭头函数 obj
nativeFn.call(obj2);//原生函数 obj2
arrowFn.call(obj2);//箭头函数 obj
setTimeout(function(){
nativeFn();//原生函数 window
arrowFn();//箭头函数 obj
},50);