Es6 箭头函数

1.单参数

function cheng(a=3){
    return a*a;
}
let cheng= (a=3)=>a*a;
console.log(cheng(9));

2.多参数

function add(a,b){
    return a+b;
}
let add = (a,b)=>a+b;   //默认返回值
console.log(add(3,9));

3.无返回值

function add(a,b){
    console.log(a+b);
}
let add = (a,b)=>{console.log(a+b)};
console.log(add(3,9));

4.多行

复制代码
function add(a,b){
    console.log(a+b);
    return a+b;
}
let add = (a,b)=>{
    console.log(a+b);
    return a+b;
};
console.log(add(3,9));
复制代码
2.如果箭头表达式仅仅就是简化了函数的命名,我们为什么要改变原来的习惯而去使用它呢?
箭头函数内部没有constructor方法,也没有prototype,所以不支持new操作。

但是它对this的处理与一般的普通函数不一样。

箭头函数的 this 始终指向函数定义时的this,而非执行时。
箭头函数不能用作构造函数,因为它没有自己的this,无法实例化;

也是因为箭头函数没有自己的this,所以箭头函数 内也不存在arguments对象。(可以用扩展运算符代替)
复制代码
var o = {
      x : 1,
      func : function() { console.log(this.x) },
      test : function() {
          setTimeout(function() {
              alert(this); //this指针转为全局
              this.func();
          }, 1000);
      }
  };
  o.test();  // TypeError : this.func is not a function
复制代码

改为箭头函数

var o = {
    x : 1,
    func : function() { console.log(this.x) },
    test : function() {
        setTimeout(() => { this.func() }, 100);
    }
};
o.test();    //这回this就指向o了

 

posted @   xuanPhoto  阅读(254)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示