標籤(空格分隔): 未分類app
單行函數體默認返回改行計算結果, 多行須要指定返回值函數
let c = (a,b)=>a+b; console.log(c(1,12)); ES5 "use strict"; var c = function c(a, b) { return a + b; }; console.log(c(1, 12));
let c = (a,b)=>{a = a+b;a--} console.log(c(1,12));//undefined let c = (a,b)=>{a = a+b;return a--};
返回對象時寫法(不然報錯)this
let c = (a,b)=>({a:a}); or let d = (a,b)=>{return {a:a}}
綁定外層函數this(簡化一個常見用法,_this = this)rest
在箭頭函數出現以前,每一個新定義的函數都有其本身的 this 值(例如,構造函數的 this 指向了一個新的對象;嚴格模式下的函數的 this 值爲 undefined;若是函數是做爲對象的方法被調用的,則其 this 指向了那個調用它的對象)。//MDNcode
ES5對象
function Person(age) { var _this = this; this.age = age; setTimeout(function growUp() { console.log(this); _this.age++; }, 1000); } var p = new Person(26);
ES6作用域
function Person(age) { this.age = age; setTimeout(()=> { console.log(this); this.age++; }, 1000); console.log(this.age); } var p = new Person(26);
使用 call 或 apply 調用io
因爲 this 已經在詞法層面完成了綁定,經過 call() 或 apply() 方法調用一個函數時,只是傳入了參數而已,對 this 並無什麼影響.console
箭頭函數不會在其內部暴露出參數(arguments ): arguments.length, arguments[0], 等等,都不會指向箭頭函數的 arguments,而是指向了箭頭函數所在做用域的一個名爲 arguments 的值(若是有的話,不然,就是 undefined。——譯者注)。function
這種狀況下,ES6 rest參數能夠替代
function foo(n) { var f = (...args) => args[0]+args.length; return f(n); } foo(1); // 1