【第二届青训营-寒假前端场】-this的指向!!

85 阅读1分钟

阮一峰的理解:www.ruanyifeng.com/blog/2018/0…

红宝书原文:

1.标准函数中: this引用的是把函数当成方法调用的上下文对象

个人理解:this是谁调用就指向谁,这里的谁就是 . 前的对象。

this:自动引用正在调用当前方法的.前的对象。

this指向的三种情况

  1. obj.fun() fun 中的 this->obj ,自动指向.前的对象
  2. new Fun() Fun 中的 this->正在创建的新对象,new 改变了函数内部的 this 指向,导致 this 指向实例化 new 的对象
  3. fun() 和匿名函数自调 this 默认->window,函数内部的 this,this 默认是指向 window 的
    bar: 1
    foo: function () { console.log(this.bar) },
  };
  
  var foo = obj.foo;
  var bar = 2;
  
  obj.foo() // 1  属于第一种情况
  foo() // 2    属于第三种情况
  this.name = "Smiley";
  this.sayName = ()=> {
    console.log(this);
    console.log(this.name); 
  };
}

let person2 = new Person();
person2.sayName.call({name: "Nicolas"});
//Person { name: 'Smiley', sayName: [Function (anonymous)] }
//Smiley

自我练习题:

    console.log('全局定义下的函数')
    console.log(this.str) //undefined
}

function fnn(){
    fn()  
    console.log('this.str'+this.str) //this.strfnn

    let fn4 = function (){
        console.log('fn4:'+this.str)  //fn4:undefined
        console.log(this)  //Window
    }
    fn4()
}
let obj={
    str:'fnn',
    fnn:fnn
}
obj.fnn()

2.箭头函数中:this引用的是定义箭头函数的上下文

  name:'zll',
  fn:()=>{
    console.log(this.name)
  }
}
obj.fn()//undefined  

var obj1={
  name:'zll',
  fn:function () {
    (()=>{
      console.log(this.name)
    })()
  }
}
obj1.fn()//zll

箭头函数中的this会保留定义该函数时的上下文:

  this.name = 'king'
  setTimeout(() => {
    console.log(this.name)
  }, 1000);
}
king()//king

function queen() {
  this.name = 'queen'
  setTimeout(function(){
    console.log(this.name)
  }, 1000);
}
queen()//undefined