JavaScript ES6-箭头函数

箭头函数

新增的定义函数的方式

    const fn= ()=>{
        console.log("hello world");
    };
      fn();

  1. 一般把箭头函数赋值给一个变量,通过变量名字调用函数
  2. 大括号里面仍然是函数体
特殊情况1:函数体中只有一句话 并且代码的执行结果就是返回值 ,可以省略大括号
//正常写法
function sum1(a,b){
    return a+b;
}

const sum2= (a,b)=>a+b;
//创建一个变量result 接一下计算结果
let result=sum2(10,20);
console.log(result);
特殊情况2: 如果形参只有一个,可以省略小括号


function twice(a){
    return a*2;
}

const twice2= a=>a*2;

let result=twice2(4);
console.log(result);


箭头函数的特点

1.没有prototype属性
        function Star(uname, age,song) {
            this.uname = uname;
            this.age = age;
            this.song=song;
        }
        console.log(Star.prototype);//Object

        const fn= (a,b)=>{
            return a+b;
        };

        console.log(fn.prototype);//undefined

2.箭头函数this为父作用域的this,不是调用时的this

普通函数this指向的是调用它的对象

箭头函数不绑定this ,箭头函数没有自己的this关键字,如果在箭头函数中使用this ,this指向箭头函数定义位置中的this

function fn(){
    console.log(this);
    return ()=>{
        console.log(this);
    }
}

const obj={name:'liu neng'};
// a相当于匿名函数的名字
const a=fn.call(obj);
a();
//输出两个相同的对象
// Object { name: "liu neng" } 
// Object { name: "liu neng" }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值