编程语言
首页 > 编程语言> > 浅聊JavaScript中的this

浅聊JavaScript中的this

作者:互联网

今天来简单学习一下JavaScript中的this关键字。

(注:所有代码均在"strict mode"环境下运行)

1.全局作用域

console.log(this); //global scope

输出结果为Window对象

image-20220807093632252

2.函数表达式

const calcAge=function (birthYear){
    console.log(2037-birthYear);
    console.log(this);
}

calcAge(2004);

注意到this输出为undefined

image-20220807093806878

3.箭头函数

const calcAgeArrow=(birthYear)=>{
    console.log(2037-birthYear);
    console.log(this);
}

calcAgeArrow(2004);

输出结果:

image-20220807093909952

我们注意到与函数表达式输出的this不同,箭头函数输出的this为Window对象,跟第一点中的this相同,这是怎么回事呢?

其实,箭头函数它没有属于自己的this关键字,这里输出的this其实是父作用域即全局作用域中的this,即为Window对象,所以与第一点中的this相同。

4.对象中的this

const jonas={
    year:1991,
    calcAge:function (){
        console.log(this);
        console.log(2037-this.year);
    }
}

jonas.calcAge();

输出结果:

image-20220807094421234

符合直觉,但是需要注意this是动态的,不是静态、一成不变的。比如我新创建一个对象ascend,并把jonas的calcAge方法赋给ascend,

const ascend={
    year:2017
};

ascend.calcAge=jonas.calcAge;
ascend.calcAge();

输出结果:

image-20220807094615688

显然,这里的this就是指向ascend,而不再是jonas了。

此外,还有Event listener中的this,new、call、apply、bind中的this等等,之后会单独出文章讨论。下面简单总结一下:

类型 this值
对象Method 调用该方法的对象
简单函数调用 undefined
箭头函数 父作用域中的this

最后,需要注意,this不指向函数本身,也不是它的变量环境!

标签:输出,console,log,浅聊,JavaScript,ascend,jonas,calcAge
来源: https://www.cnblogs.com/ascendho/p/16558508.html