深入理解ES6——函数

1.    ES6中默认参数值对arguments对象的影响:

    在ES5中非严格模式下,命名参数的变化会同步更新到arguments对象中,例如:

function mixArgs(first,second){
  console.log(first===arguments[0]);     //true
  console.log(second===arguments[1]);    //true
  first = "c";
  second = "d";
  console.log(first===arguments[0]);    //true
  console.log(second===arguments[1]);   //true
}    

  在ES5的严格模式下,arguments对象不会随着命名参数的变化而变化。

function mixArgs(first,second){
  "use strict";
  console.log(first===arguments[0]);     //true
  console.log(second===arguments[1]);    //true
  first = "c";
  second = "d";
  console.log(first===arguments[0]);    //false
  console.log(second===arguments[1]);   //false
}  

     在ES6中,如果一个函数使用了默认参数值,则无论是否显式定义了严格模式,arguments对象的行为都与ES5严格模式下保持一致。默认参数值的存在使得arguments对象保持与命名参数分离。

function mixArgs(first,second="b"){
  console.log(arguments.length);         //1
  console.log(first===arguments[0]);     //true
  console.log(second===arguments[1]);    //false
  first = "c";
  second = "d";
  console.log(first===arguments[0]);    //false
  console.log(second===arguments[1]);   //false
}  
mixArgs("a");

在引用参数默认值时,只允许引用前面参数的值,即先定义的参数不能访问后定义的参数,例如:

function add(first = second, second){
  return first + second;
}
console.log(add(1,1));           //2
console.log(add(undefined,1));   // 抛出错误

2.    不定参数是一个数组,使用限制有两个:首先,每个函数最多只能声明一个不定参数,而且一定要放在所有参数的末尾;其次不定参数不能用于对象字面量setter之中(因为对象字面量setter的参数有且只能有一个)。

3.    块级函数和let函数表达式类似,一旦执行过程流出了代码块,函数定义立即被移除。二者的区别是:在该代码块中,块级函数会被提升到块的顶部,而用let定义的函数表达式不会被提升。

在严格模式下:

if(true){
  console.log(typeof doSomething);   // "function"
  function doSomething(){

  }
}
if(true){
  console.log(typeof doSomething);   // 抛出错误
  let doSomething = function(){

  }
}
但在非严格模式下,块级函数不再是提升至代码块的顶部,而是提升至外围函数或全局作用域的顶部。


4.    箭头函数与传统函数的区别:

  • 没有this、super、arguments和new.target绑定。箭头函数中的this、super、arguments和new.target这些值由外围最近一层非箭头函数决定。
  • 不能通过new关键字调用。箭头函数没有[[Construct]]方法,所以不能被用作构造函数,如果通过new关键字调用箭头函数,程序会抛出错误。
  • 没有原型。由于不可以通过new关键字调用箭头函数,因而没有构建原型的需求,所以箭头函数不存在prototype这个属性。
  • 不可以改变this的绑定。函数内部的this值不可被改变,在函数的生命周期内始终保持一致。
  • 不支持arguments对象。箭头函数没有arguments绑定,所以必须通过命名参数和不定参数这两种形式访问函数的参数。
  • 不支持重复的命名参数。无论是在严格还是非严格模式下,箭头函数都不支持重复的命名参数;而在传统函数的规定中,只有在严格模式下才不能有重复的命名参数。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值