ES6 基本语法

一、 常量
const PI = 3.1415926
console.log(PI)
二、 作用域
// let 实现块作用  
const callbacks2 = []
for (let j = 0; j <= 2; j++) {
    callbacks2[j] = function() {
        return j * 2
    }
}
通过花括号限制作用域
{
    function foo() {
        return 1
    }

    console.log("foo()===1", foo() === 1)
    {     
        function foo() {
            return 2
        }

        console.log("foo()===2", foo() === 2)
    }
    console.log("foo()===1", foo() === 1)
}

箭头函数

=> : 箭头函数等同于

ES5 ES6
函数 箭头函数
function () { } () => { }
ES3,ES5 的写法
{
  // ES3,ES5
  var evens = [1, 2, 3, 4, 5];
  var odds = evens.map(function(v) {
    return v + 1
  });
  console.log(evens, odds);
};
ES6 箭头函数的写法
{
  // ES6
  let evens = [1, 2, 3, 4, 5];
  let odds = evens.map(v => v + 1);
  console.log(evens, odds);
}
this 指向

类的实例

{
  var factory = function() {
    this.a = 'a';
    this.b = 'b';
    this.c = {
      a: 'a+',
      b: () => {
        return this.a //这里指向的是 定义factory对象实例的 this.a
      }
    }
  }
  console.log(new factory().c.b());
}
默认参数
{
  // ES6 默认参数
  function f(x, y = 7, z = 42) {
    return x + y + z
  }
  console.log(f(1, 3));
} 
必选参数的检查操作
{
  function checkParameter() {
    throw new Error('can\'t be empty')
  }
  function f(x = checkParameter(), y = 7, z = 42) {
    return x + y + z
  }
  console.log(f(1));
  try {
    f()
  } catch (e) {
    console.log(e);
  } finally {}
} 

你可能感兴趣的:(ES6 基本语法)