主要讲解:es6
1. rest参数 2. 严格模式 3. name属性 -- 返回函数的函数名 4. 箭头函数 -- 用 "=>" 定义函数
...arguments <=> ...[...] 引入rest参数其目的是为了获取函数的多余参数 <=> 数组的扩展运算符...的逆向形式 将参数数列转为一个数组 <=> 将一个数组转为逗号分隔的参数序列 function push(arr,...items){ //有点安能辨我是雄雌的感受 if(Array.isArray(items)){ array = array.concat(items); // rest参数的状况 }else{ array.push(...items); // 数组的扩展运算的状况 } } //rest参数 push([],1,23,4,45,56) //[1,23,4,45,56] //数组的扩展运算 push([],...[1,23,4,45,56]); //[1,23,4,45,56] 注意: 1.rest参数必须位于函数参数末尾,且只能存在一个rest参数,不然报错 2.函数的length属性不包括rest参数,就跟止步于默认值参数同样,不肯定的事情不考虑在内
es5中函数内部能够设定严格模式,es6中函数参数使用了默认值、解构赋值、或者扩展运算符的话就不能设定严格模式 伪代码: function doSomething(...items){ 'use strict'; ... } //Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list //因为代码中基本没有在函数内部使用严格模式的状况,这个就很少了解了
function push(arr,...items){} push.name; //"push" push.bind({}).name //"bound push" let sayHi = function(){} sayHi.name //"sayHi" let sayHi = function realName(){} sayHi.name //"realName" let sayHell = new Function('x','y','console.log(x,y)'); sayHell.name //"anonymous" sayHell.bind({}).name //"bound anonymous" //仅仅知道有这么一个属性,具体用处未知
let sayHi = name => name; 等价于: let sayHi = function(name){ return name; } 用法: i.单个参数时,可直接写参数名 ii.0个或两个及两个以上参数必须加括号 let f = () => 5; let f = (x,y) => x+y; iii.函数代码块多于一条语句,就要使用大括号括起来 let f = (x,y) => { ...}
**箭头函数除了简化函数的写法,特别是匿名函数.另外一个重要功能就是绑定定义时所在的做用域,而非运行时动态的做用域**
像click,setTimeout,setInterval这种运行时动态改变做用域的,写成箭头函数的形式则this仍然为代码定义处的this //计时器一个 function Timer(){ this.count = 0; setInterval(() => {this.count++;},1000); } let t = new Timer(); 等价的写法: function Timer(){ this.count = 0; let __that = this; setInterval(function(){__that.count++;},1000); } //嵌套的状况,能够以此类推.其实就是在外层做用域建立一个变量指向this,而后内层使用.每一层都会建立该层的this指向供下一层使用.
若有bug请指正Thanks♪(・ω・)ノ!数组