JS中的this指向问题()

  1. 在全局作用域
    =>this -> window
     1<script>    console.log(this); //this->window </script>
  2. 在普通函数中

    =>this取决于谁调用,谁调用我,this就指向谁,跟如何定义无关

     1var obj = {    
     2  fn1:function() {     
     3    console.log(this);     
     4  },        
     5  fn2:function(){      
     6    fn3()     
     7  }        
     8}       
     9function fn3() {    
    10  console.log(this);    
    11}    
    12fn3();//this->window    
    13obj.fn1();//this->obj 
    14obj.fn2();//this->window
    
  3. 箭头函数中的this

    箭头函数没有自己的this,箭头函数的this就是上下文中定义的this,因为箭头函数没有自己的this所以不能用做构造函数。

     1var div = document.querySelector('div'); 
     2var o={     
     3  a:function(){      
     4    var arr=[1];      
     5    //就是定义所在对象中的this     
     6    //这里的this—>o    
     7    arr.forEach(item=>{   
     8      //所以this -> o      
     9      console.log(this);  
    10    })      
    11  },   
    12  //这里的this指向window o是定义在window中的对象   
    13  b:()=>{     
    14    console.log(this);     
    15  },      
    16  c:function() {   
    17    console.log(this); 
    18  }    
    19}   
    20div.addEventListener('click',item=>{  
    21  console.log(this);//this->window 这里的this就是定义上文window环境中的this   
    22});   
    23o.a(); //this->o   
    24o.b();//this->window 
    25o.c();//this->o 普通函数谁调用就指向谁
  4. 事件绑定中的this

    事件源.onclik = function(){ } //this -> 事件源

    事件源.addEventListener(function(){ }) //this->事件源

     1var div = document.querySelector('div');  
     2div.addEventListener('click',function() {  
     3  console.log(this); //this->div  
     4});         
     5div.onclick = function() {    
     6  console.log(this) //this->div    
     7}
  5. 定时器中的this

    定时器中的this->window,因为定时器中采用回调函数作为处理函数,而回调函数的this->window

     1setInterval(function() {     
     2  console.log(this); //this->window  
     3},500)       
     4setTimeout(function() {    
     5  console.log(this); //this->window   
     6},500)
  6. 构造函数中的this

    构造函数配合new使用, 而new关键字会将构造函数中的this指向实例化对象,所以构造函数中的this->实例化对象

    new关键字会在内部发生什么

     1//第一行,创建一个空对象obj。 
     2var obj  ={}; 
     3//第二行,将这个空对象的__proto__成员指向了构造函数对象的prototype成员对象.
     4obj.__proto__ = CO.prototype; 
     5//第三行,将构造函数的作用域赋给新对象,因此CA函数中的this指向新对象obj,然后再调用CO函数。于是我们就给obj对象赋值了一个成员变量p,这个成员变量的值是” I’min constructed object”。 
     6CO.call(obj); 
     7//第四行,返回新对象obj。
     8return obj;
     1function Person(name,age) {   
     2  this.name = name;      
     3  this.age = age;   
     4}    
     5var person1 = new Person();   
     6person1.name = 'andy'; 
     7person1.age = 18;   
     8console.log(person1);//Person {name: "andy", age: 18}   
     9var person2 = new Person();  
    10person2.name = 'huni';   
    11person2.age = 20;    
    12console.log(person2);// Person {name: "huni", age: 20
个人笔记记录 2021 ~ 2025