ES6常量作用域箭头函数默认参数对象代理语法

最近刚接触ES6,把基础语法整理一番。

1、常量

const PI = 3.1415926
console.log(PI)

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)
}

3、箭头函数

{
  let evens = [1, 2, 3, 4, 5];
  let odds = evens.map(v => v + 1);
  console.log(evens, odds);
} 
{
  var factory = function() {
    this.a = 'a';
    this.b = 'b';
    this.c = {
      a: 'a+',
      b: () => {
        return this.a
      }
    }
  }
  console.log(new factory().c.b());//输出a
}

4、默认参数

{
  function f(x, y = 7, z = 42) {
    return x + y + z
  }
  console.log(f(1, 3));//输出46
}
{
  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);//输出50
  } finally {}
} 
 {
  // ES6 可变参数
  function f(...a) {
    var sum = 0;
    a.forEach(item => {
      sum += item * 1
    });
    return sum
  }
  console.log(f(1, 2, 3, 6));//输出12
}
{
  // ES6 利用扩展运算符合并数组
  var params = ['hello', true, 7];
  var other = [
    1, 2, ...params
  ];
  console.log(other);//输出(5) [1, 2, "hello", true, 7]
}

5、对象代理

{
  // ES6
  let Person = {
    name: 'es6',
    sex: 'male',
    age: 15
  };

  let person = new Proxy(Person, {
    get(target, key) {
      return target[key]
    },
    set(target,key,value){
      if(key!=='sex'){
        target[key]=value;
      }
    }
  });

  console.table({
    name:person.name,//es6
    sex:person.sex,//male
    age:person.age//15
  });

  try {
    person.sex='female';
  } catch (e) {
    console.log(e);
  } finally {
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值