0
点赞
收藏
分享

微信扫一扫

this指向(普通函数、箭头函数)

小a草 2022-03-15 阅读 45

普通函数中的this

1.谁调用了函数或者方法,那么这个函数或者对象中的this就指向谁

let getThis = function(){
console.log(this)
}
let obj = {
name:""Jack",
getThis:function(){
console.log(this)
}
}
//getThis()方法是由window在全局作用域中调用的,所以this指向调用该方法的对象,即window
getThis()//window
obj.getThis() //obj

2.匿名函数中的this:匿名函数的执行具有全局性,则匿名函数中的this指向是window,而不是调用该匿名函数的对象;

let obj = {
getThis:function(){
return function(){
console.log(this)
}
}
}
obj.getThis()() //window

上面代码中,getThis()方法是由obj调用,但是obj.getThis()返回的是一个匿名函数,而匿名函数中的this指向window,所以打印出window。如果想在上述代码中使用this指向调用该方法的对象,可以提前把this传值给另外一个变量(_this或者that)

1.箭头函数中的this

  1. 箭头函数中的this是在函数定义的时候就确定下来的,而不是在函数调用的时候确定的;
  2. 箭头函数中的this指向父级作用域的执行上下文;(技巧:因为javascript中除了全局作用域,其他作用域都是由函数创建出来的,所以如果想确定this的指向,则找到离箭头函数最近的function,与该function平级的执行上下文中的this即是箭头函数中的this)
  3. 箭头函数无法使用apply、call和bind方法改变this指向,因为其this值在函数定义的时候就被确定下来。

列1:首先,距离箭头函数最近的是getThis(){},与该函数平级的执行上下文是obj中的执行上下文,箭头函数中的this就说下注释处的this,即obj.

let obj = {
getThis:function(){
return ()=>{
console.log(this)
}
}
}
obje.getThis()()//obj

 列2:该段代码中存在2两个箭头函数,this找不到对应的function(){},所以一直往上照到指向window。

//代码中有两个箭头函数,由于找不到对应的function,所以this会指向window对象。
let obj = {
getThis:() =>{
return () =>{
console.log(this)
}
}
}
obj.getThis()();//window
举报

相关推荐

0 条评论