脚本宝典收集整理的这篇文章主要介绍了es6入门笔记,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
常量const
const a = 1;
a +=2;
console.LOG(a);
//报错 VM6833:2 Uncaught TyPEError: Assignment to constant VARiable.
//常量只读,不可以更改
列表项目
@L_777_1@/es6作用域
举个栗子:
//ES5
(function(){
var arr = [];
for(var i =0;i<=2;i++){
arr[i]=function(){
return i+1;
}
}
arr[0]();//4,i并没有进入循环,而是在循环完,i++到i=3;
arr[1]();//4 一个闭包的存在,当执行arr[2]()时,i已经是3
})()
--------
//es6
{
let arr = [];
for(let i = 0;i<=2;i++){
arr[i] = ()=>i+1;
}
arr[0]();//1
arr[1]();//2
}
总结: es5要通过立即执行函数对作用域进行隔离,es6只需要{}即可这样就不会污染全局变量,可以多次使用同样的变量
let变量声明
{
let a = 1;
}
console.log(a);//报错 a is not defined
//不要在声明之前使用,在语法上,称为“暂时性死区”(temporal dead zone,简称 TDZ)。
var tmp = 123;
if (true) {
tmp = 'abc'; // ReferenceError
let tmp;
}
批量声明
{
let [a,b,c]=[1,2,3];
console.log(typeof a);//number
}
循环
for in&&for of
var arr=[1,3,4]
for(var i in arr){
console.log(i);
}
//0,1,2
for(var i of arr){
//1,3,4;
}
箭头函数
es5:
(function(i){
i+=1;
console.log(i);
})(1) //2
es6:
((i)=>{
i+=1;
console.log(i);
})(1) //2
es6中function可以省略,如果括号里只有返回的表达式,那么花括号和return关键字也可以省略。
//es5
{
var factory = function(){
this.a = 'a';
this.b = 'b';
this.c = {
a:'a+',
b:function(){
return this.a;
}
}
}
console.log(new factory().c.b())//a+
}
//es6
{
var factory = function(){
this.a = 'a';
this.b = 'b';
this.c = {
a:'a+',
b:()=>this.a
}
}
console.log(new factory().c.b())//a
}
es5实例的this指向是该函数被调用的指向(该函数是被哪个对象所调用时的就是this)
箭头函数中的this指向是定义时的指向(new factory()实例的指向)
以上是脚本宝典为你收集整理的es6入门笔记全部内容,希望文章能够帮你解决es6入门笔记所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。