码迷,mamicode.com
首页 > 其他好文 > 详细

es6箭头函数

时间:2017-12-19 01:32:07      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:function   log   tle   运行   win   apply   window   too   括号   

一:箭头函数的格式 

  a:一种为只有一条语句,可以省略{}和return。

x => x * x;

    相当于:

function(x) {
    return x * x;
}

  b:一种为多条语句,不可以省略{}和return。

x => {
  if (x > 0) {
    return 1;
  }
  return 2;
}

    相当于:

function(x){
  if (x > 0) {
    return 1;
  }
  return 2;
}

  注意:

    a.当无参数时或有多个参数时,需要用括号()括起来。

(x, y)=> x + y;

    b.当省略{}和return时,返回了一个对象,对象要用括号()括起来。

x=> ({color:"red"});

 

二:箭头函数的this

  a.箭头函数没有自己的 this,其内部的 this 绑定到它的外围作用域。对象内部的箭头函数若有this,则指向对象的外围作用域。

技术分享图片
window.color = "red";
//let 声明的全局变量不具有全局属性,即不能用window.访问
let color = "green"; let obj = { color: "blue",
   getColor: () => {
     return this.color;//this指向window
   } }; let sayColor = () => { return this.color;//this指向window };
obj.getColor();//red sayColor();//red
技术分享图片

   b.箭头函数无法使用 call()或 apply()来改变其运行的作用域。

技术分享图片
window.color = "red";
let color = "green";
let obj = {
  color: "blue"
};
let sayColor = () => {
  return this.color;
};
sayColor.apply(obj);//red
技术分享图片

es6箭头函数

标签:function   log   tle   运行   win   apply   window   too   括号   

原文地址:http://www.cnblogs.com/beimingbingpo/p/8059071.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!