es其他常用功能

es6除了模块化,class,promise,还有一些其他的常用功能。
1、let/const
let是定义一个变量,但是这个变量可以重新赋值,const是定义一个常量,这个常量不能重新赋值
let i = 10; i = 100; // 正确
const j = 20; j = 200; // 报错
2、多行字符串/模板变量
// JS
var name = 'zhangsan', age = 20, html = '';
html = '<div>'
html += ' <p>' + name + '</p>';
html += ' <p>' + age + '</p>';
html +='</div>'



// es6
const name = 'zhangsan', age = 20;
const html = `
  <div>
    <p>${name}</p>
    <p>${age}</p>
  </div>
`;

一个特点是反引号,一个${}引入变量,代码易读

3、解构赋值
// JS
var obj = {a:100, b:200}
var a = obj.a;
var b = obj.b;


var arr = ['xxx', 'yyy', 'zzz'];
var x = arr[0];


//ES6
const obj = {a:10, b:20, c:30};
const {a, c} = obj;
console.log(a);
console.log(c);


const arr = ['xxx', 'yyy', 'zzz'];
const [x, y, z] = arr;
console.log(x);
console.log(y);
console.log(z);



4、块级作用域
js没有块级作用域,会埋下坑
// JS
var obj = {a:100, b:200}
for (var item in obj){
  console.log(item);
}
console.log(item) // b


// ES6
const obj = {a:100, b:200}
for(let item in obj){
  console.log(item);
}
console.log(item);// undefined
5、函数默认参数
//JS
function fn(a,b){
  if (b == null) {
    b = 0;
  }
}

//ES6
function fn(a, b=0){
 
}




6、箭头函数
//JS
var arr = [1, 2, 3, 4, 5];
arr.map(function(item){
  return item + 1;
})


//ES6
const arr = [1, 2, 3, 4, 5];
arr.map(item => item +1);



function fn(){
  console.log('real', this); // {a:100}
  var arr = [1, 2, 3];
  arr.map(() => {
    console.log(this); // {a:100}
  })
  arr.map(function(){
    console.log(this)
  })
}
fn.call({a: 100})
原文地址:https://www.cnblogs.com/wzndkj/p/10961880.html