箭头函数详解

什么是箭头函数

es6新增了使用胖箭头(=>)语法定义函数表达式的能力。任何可以使用函数表达式的地方,都可以使用箭头函数。
函数内部有一个特殊的对象是this,它在标准函数和箭头函数中有不同的行为。
标准函数中,this引用的是把函数当成方法调用的上下文对象,这时候通常称其为this值。
1、全局作用下,this指向window;
2、在网页的全局上下文中调用函数时,this指向window;
3、被嵌套的函数独立调用时,this默认指向window;
4、匿名自调执行函数(具有全局性)中内部的this指向window;
箭头函数中,this引用的是定义箭头函数的上下文。

1.例题一

函数为标准函数时的情形:

var birth = 1921;
var obj = {
    birth: 1949,
    getAge: function () {
        var birth = 1922; //迷惑项1
        console.log(this, this.birth);// obj 1949
        return (function () {
            var birth = 1923; //迷惑项2
            console.log(this, this.birth);// window 1921
            return (function () {
                var birth = 1924; //迷惑项3
                console.log(this, this.birth);// window 1921
                return (function () {
                    var birth = 1925; //迷惑项4
                    console.log(this, this.birth);// window 1921
                    return new Date().getFullYear() - this.birth;
                })();
            })();
        })();
    }
};
console.log(obj.getAge());   //102

2.例题二

函数是箭头函数的情形:(在实际项目中经常看到,使用setInterval,forEach等函数方法去改变this指向上级时,变标准函数为箭头函数居多。)

var birth = 1921;
var obj = {
    birth: 1949,
    getAge: function () {
        var birth = 1922; //迷惑项1
        console.log(this, this.birth);// obj 1949
        return (() => {
            var birth = 1923; //迷惑项2
            console.log(this, this.birth);// obj 1949
            return (() => {
                var birth = 1924; //迷惑项3
                console.log(this, this.birth);// obj 1949
                return (() => {
                    var birth = 1925; //迷惑项4
                    console.log(this, this.birth);// obj 1949
                    return new Date().getFullYear() - this.birth;
                })();
            })();
        })();
    }
};
console.log(obj.getAge()); // 74

3.例题三

如果这几个箭头函数中有一个变为标准函数,它将影响下一个箭头函数的指向,例如:

var birth = 1921;
var obj = {
    birth: 1949,
    getAge: function () {
        var birth = 1922; //迷惑项1
        console.log(this, this.birth);// obj 1949
        return (() => {
            var birth = 1923; //迷惑项2
            console.log(this, this.birth);// obj 1949
            return (function () {
                var birth = 1924; //迷惑项3
                console.log(this, this.birth);// window 1921
                return (() => {
                    var birth = 1925; //迷惑项4
                    console.log(this, this.birth);// window 1921
                    return new Date().getFullYear() - this.birth;
                })();
            })();
        })();
    }
};
console.log(obj.getAge()); // 74
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值