ES6之箭头函数

来源:互联网 发布:java和asp.net的区别 编辑:程序博客网 时间:2024/05/18 09:16

箭头函数

箭头函数主要的作用是简化回调函数的作用域使其和所在位置的上下文的作用域保持一致,方便this的调用

在ES6的新特性中,不管是let还是箭头函数的申明都已经失去了提升的效果(将定义的变量和函数提升到作用域的最顶端),所以如果在定义变量之前引用了变量就会出现暂时性死区。如下

foo(); //Uncaught TypeError: foo is not a functionvar foo = () => {    alert(1)}console.log(f);//Uncaught ReferenceError: f is not definedlet f = 1;
var foo = () => {    alert(1)}foo(); // 1let f = 1;console.log(f);// 1

函数表达式

var fn = item => {    document.write(item + 1 + "<br/>")};

函数体

var bar = item =>{    document.write(item - 1 + "<br/>")}// 函数

内联函数

[5,8,9].map(item => {    fn(item);},()=>{    document.write("<br/>")});[5,8,9].map(item => {    bar(item);    document.write("<br/>")})

自执行函数

!(fn = () => {    console.log(1);})();

隐式返回值

foo = (x)=>x+1;console.log(foo(1)); // 2

箭头函数中的arguments

arguments 在箭头函数中 arguments被隐藏 ,如果单纯使用arguments将会视为调用变量。

var arguments = [0];arg = (bool) => {    console.log(arguments[0]);}arg(false);// 0

可以使用 …arguments ,简写…args,也可以叫做其他名字, …不变

var arguments = [0];arg = (...args) => {    console.log(args[0]);}arg(false);// false

 this的指向

var a = {    a:"one",    timeout:function(){        setTimeout(()=>{            alert(this.a);        },1000)    },    timeout2:function(){        setTimeout(function(){            console.log(this.a);        },1000)    }}a.timeout(); // onea.timeout2();  // 你猜猜?去亲自试试吧!

箭头函数的陷阱

document.addEventListener('click',()=>{    console.log(this);//window});document.addEventListener('click',function(){    console.log(this);//document});

由此可见,在一些具有默认非Window指向的this功能的时候,箭头函数会将此功能覆盖使得this变为指向Window

小结

箭头函数主要的作用是简化回调函数里面this指向的解决办法,但是在某些情况下却会起到相反的作用,所以在使用箭头函数的时候要多多注意,最好只是在内联函数部分使用,使用的时候最好带上花括号,这样可以使代码看起来更加清晰,结构明了。另外,要注意箭头函数的暂时性死区,最好是在引用前就将声明写上。