箭头函数和常规函数中的this

今天继续来讲讲JavaScript中的this关键字。

1.一个引例
const ascend={
	firstName:'ascend',
	year:2004,
	calcAge:function(){
	console.log(this);
	console.log(2037-this.year);
},
    greet:()=>console.log(`Hey ${this.firstName}`),
};
	ascend.greet();

大家试想一下上述代码的输出结果是什么呢?答案可能会出乎你的意料,

image-20220808093852374

为什么会是undefined呢?其实如果有看过我之前的那篇博客或者有这方面的知识其实就明白了,箭头函数没有属于自己的this关键字,它的this是父作用域中的this,也就是这里的全局作用域。

但是如果我们在该代码上面加上一段代码,

var firstName='ascend';

image-20220808094341474

验证了箭头函数的this是父作用域中的this。

现在我们将代码修改成下面这样:

const ascend={
    firstName:'ascend',
    year:2004,
    calcAge:function(){
        console.log(this);
        console.log(2037-this.year);

        const isMillenial=function (){
            console.log(this.year>=1981 && this.year<= 1996);

        };
        isMillenial();

    },
    greet:()=>console.log(`Hey ${this.firstName}`),
};

ascend.greet();
ascend.calcAge();

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yxPqb8gl-1659946087078)(https://s2.loli.net/2022/08/08/efF2b9aKW6QGdJ8.png)]

我们可以发现,isMillenial中的this值为undefined,这跟我们上次讲到的函数表达式的this值为undefined一样,所以不要产生误解,认为在对象方法里面this就应该指向对象,这是不对的。

2.解决方案
  • 平庸方法
const ascend={
    firstName:'ascend',
    year:2004,
    calcAge:function(){
        console.log(this);
        console.log(2037-this.year);

        const self=this;
        const isMillenial=function (){
            console.log(self);
            console.log(self.year>=1981 && self.year<= 1996);

        };
        isMillenial();

    },
    greet:()=>console.log(`Hey ${this.firstName}`),
};

就是在isMillenial函数外用变量先将this存储起来。

  • 箭头函数(推荐)
const ascend={
    firstName:'ascend',
    year:2004,
    calcAge:function(){
        console.log(this);
        console.log(2037-this.year);
        
        const isMillenial= ()=>{
            console.log(this);
            console.log(this.year>=1981 && this.year<= 1996);

        };
        isMillenial();

    },
    greet:()=>console.log(`Hey ${this.firstName}`),
};

就是将isMillenial改写成箭头函数的形式,因为我们知道箭头函数没有属于自己的this,而是它父作用域中的this,此处isMillenial函数的父作用域是成员方法calcAge,因而输出结果为

image-20220808160652433

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值