今天继续来讲讲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();
大家试想一下上述代码的输出结果是什么呢?答案可能会出乎你的意料,
为什么会是undefined呢?其实如果有看过我之前的那篇博客或者有这方面的知识其实就明白了,箭头函数没有属于自己的this关键字,它的this是父作用域中的this,也就是这里的全局作用域。
但是如果我们在该代码上面加上一段代码,
var firstName='ascend';
验证了箭头函数的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,因而输出结果为