当前位置:   article > 正文

JS-常见this指向问题_this 选择上一级

this 选择上一级
  • 如何绑定this的取值

  • 如何获取函数外层的this

一:首先解决如何绑定this取值:

比如下面代码:

  1. const person = {
  2. name:"thc",
  3. age: 18,
  4. test: function(){
  5. console.log(this);
  6. }
  7. }
  8. person.test();
  9. const test = person.test;
  10. test();

控制台输出:

可见

person.test():  输出的是person的对象object

test():输出的是window

解决方法:绑定this取值,通常用bind进行绑定

修改后的代码例如:

  1. const person = {
  2. name:"thc",
  3. age: 18,
  4. test: function(){
  5. console.log(this);
  6. }
  7. }
  8. person.test();
  9. const test = person.test.bind(person);
  10. test();

控制台输出:

结论1:与大多语言不一样,在JavaScript中,函数里的this指向的是执行时的调用者,而非定义时所在的对象。


二:如何获取函数外层的this

还是从代码的角度去讲解,如下:

  1. const person1 = {
  2. test:function(){
  3. setTimeout(function(){
  4. console.log(this)
  5. },1000);
  6. }
  7. };
  8. person1.test(); // 输出window
//注释:setTimeout(func, time)表示time时间后执行func函数

从上述结果可以表明,函数输出的this是window,并没有输出person这个对象

解决方法:当我们需要去获取外层的this时,常用两种方法

第一种:在外层将this记录下来,例如:

  1. const person1 = {
  2. test:function(){
  3. let outer = this
  4. setTimeout(function(){
  5. console.log(outer)
  6. },1000);
  7. }
  8. };
  9. person1.test(); // 输出{test: f}

第二种: 使用箭头函数,箭头函数不重新绑定this的取值,它会绑定上层的object,例如:

  1. const person2 = {
  2. test:function(){
  3. setTimeout(() => {
  4. console.log(this)
  5. },1000);
  6. }
  7. };
  8. person2.test(); // 输出{test:f}

结论二:箭头函数不重新绑定this的取值

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/63532
推荐阅读
相关标签
  

闽ICP备14008679号