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