es6的箭头函数
1.使用語(yǔ)法 : 參數(shù) => 函數(shù)語(yǔ)句;
分為以下幾種形式 :
(1) ()=>語(yǔ)句
(? )=>?statement 這是一種簡(jiǎn)寫(xiě)方法省略了花括號(hào)和return 相當(dāng)于 ()=>{return statement;}
?這和 匿名函數(shù) function(){return statement;}等同
零個(gè)參數(shù)用()表示;
(2)? ? (? ) =>{多行語(yǔ)句}
多行語(yǔ)句就不能省略花括號(hào)了,沒(méi)有寫(xiě)return則返回 undefined;
(3)? ? x =>{statement return y}? ?x=>statement 當(dāng)只有一個(gè)參數(shù)時(shí)可以省略小括號(hào);
?這和 匿名函數(shù) function(x){ statement return y;}等同
(4)? ? ?(x,y,z) = >{statement return z}? ?(x,y,z)=>statement? 多個(gè)參數(shù)必須有小括號(hào);
(5)? ? ()=>({ob:"this is object"})?
使用簡(jiǎn)寫(xiě)方式當(dāng)返回值是一個(gè)對(duì)象時(shí)需要加上小括號(hào);這是因?yàn)榛ɡㄌ?hào)在js中表示可執(zhí)行代碼段也表示對(duì)象集合所以為了避免錯(cuò)誤必須有小括號(hào);
使用()=>{return {object :" obj "}} 則不必添加小括號(hào)(添加了也不會(huì)有錯(cuò));
2.箭頭函數(shù)的特性
(1)?箭頭函數(shù)內(nèi)部沒(méi)有constructor方法,也沒(méi)有prototype,所以不支持new操作。
new (() => {}) //此處會(huì)報(bào)錯(cuò)
(2)它對(duì)this的處理與一般的普通函數(shù)不一樣。箭頭函數(shù)的 this?始終指向函數(shù)定義時(shí)的 this,而非執(zhí)行時(shí),并且call和aply無(wú)法改變this的指向;
window.color = "red"; let color = "green"; let obj = {color: "blue" }; let sayColor = () => {return this.color; }; sayColor.apply(obj);//red?
?
轉(zhuǎn)載于:https://www.cnblogs.com/lizhiwei8/p/7677095.html
總結(jié)