标签(空格分隔): 未分类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