前端每日一练:如何理解箭头函数没有 this​,做完这几题你肯定会明白透彻

所谓的没有 this,不是箭头函数中没有 this 这个变量,而是箭头函数不绑定自己的 this,它们会捕获其所在上下文的 this 值,作为自己的 this 值。这对于回调函数特别有用,可以避免传统函数中常见的 this 指向问题。例如,在对象方法中使用箭头函数可以确保 this 保持一致。

习题练习

第一题
var name =222
var a ={
    name:111,
    say:function(){
        console.log(this.name)
    }
}
var fun = a.say
fun()//是 fun.call(window)的简写 //222
a.say()// a.say.call(a)//111
var b ={
    name:333,
    say:function(fn){
        fn()//fn.call(window)的简写 //222
    }
}
b.say(a.say)
b.say=a.say
b.say()//b.say.call(b)//33
 第二题
var x =11;
var obj={
    x:22,
    say:()=>{
        console.log(this.x);//
    }
}
obj.say()//11
//箭头函数本身没有this,它的this是继承自父执行上下文的this,比如这里的箭头函数this.x,箭头函数本身域say平级,类似于Key:value的形式,也就是箭头函数本身所处的环境是obj, 所以它的this指向obj外侧的window,故输出 11
第三题
globalThis.a = 100;​
function fn() {​
  return {​
    a: 200,​
    m: function() {​
      console.log(this.a);​
    },​
    n: ()=>{​
      console.log(this.a);​
    },​
    k: function() {​
      return function() {​
        console.log(this.a)​
      }​
    }​
  };​
}​
​
const fn0 = fn();​
fn0.m(); // 输出 200,this 指向 {a, m, n}​
fn0.n(); // 输出 100,this 指向 globalThis​
fn0.k()(); // 输出 100, this 指向 globalThis​
​
const context = {a: 300}​
const fn1 = fn.call(context); // 改变箭头函数 this 指向​
fn1.m(); // 输出 200,this 指向 {a, m, n}​
fn1.n(); // 输出 300,this 指向 context​
fn1.k().call(context); // 输出 300,this 指向 context
 第四题
var name = 'window'​
​
const person1 = {​
  name: 'person1',​
  foo1: function() {​
    console.log(this.name)​
  },​
  foo2: () => {​
    console.log(this.name)​
  },​
  foo3: function() {​
    return function() {​
      console.log(this.name)​
    }​
  }​
}​
​
const person2 = {​
  name: 'person2'​
}​
person1.foo1() // person1​
person1.foo1.call(person2) // person2​
​
person1.foo2() // window​
person1.foo2.call(person2) // window​
​
person1.foo3()() // window​
person1.foo3.call(person2)() // window
第五题
let length = 10;​
​
function fn() {​
  return this.length + 1​
}​
​
const obj = {​
  length: 5,​
  test1: function() {​
    return fn()​
  }​
}​
​
obj.test2 = fn;​
​
console.log(obj.test1()); // window 的窗口数 (window.length 是页面子窗口数量)​
console.log(fn() === obj.test2()) // false

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值