js this

73 阅读1分钟

this为指向

普通函数中的this取值

1. 谁调用函数this指向谁

// this是指向,普通函数中谁调用this就指向谁。
    let obj = {
        lookThis(){
            console.log(this);               
        },
        name:"ws"
    }
    obj.lookThis() //obj

2.事件绑定函数中的this指向事件源

    let obj = {
        name:"ws"
    }
    obj.lookThis = function(){
        console.log(this);                       
    }
    obj.lookThis()

    document.onclick = function(){
        console.log(this);                       
    }// document

3.不受定义环境影响,受调用对象影响

    // 开启严格模式
    "use strict";
    function lookThis(){
        console.log(this);                       
    }
    lookThis() // undefind,因为找不到调用者
    window.lookThis() //window

    let arr = [1,2,3]
    arr.lookThis = lookThis
    arr.lookThis() // arr

4. 构造函数中的this指向其创建的实例

 function obj (sex){
        console.log(this); 
        this.sex = sex
 }
 let ws = new obj('男') // {sex:'男'} 

箭头函数中的this取值

1 箭头函数没有绑定的this值,其值为上层作用域的this值

    "use strict";
    // 1.箭头函数没有绑定本身的this,其值向上层作用域查询
    let that = this
        console.log(that); //window

    let fn = () => console.log(this == that);
    fn()//true

   let obj = {
    // t = window
    t:this,
    fn1:()=>{
        console.log(this);
        return this
    },
    fn2(){
        console.log(this);        
        return this
    }
   }
   obj.fn1() // window
   obj.fn2() // obj
   console.log(obj.fn1() == obj.t); // true

    // 3.构造函数中实例的方法如果是箭头函数则this指向为当前实例,因为他箭头函数没有this向上寻找则为其本身。
    function cObj () {
        console.log(this);
        this.a = () => this
        this.b = function(){
            console.log(this);
            return this
        }
    }
    
    let obj = new cObj()
    console.log(obj.a() == obj.b());//true

2 箭头函数不受调用者影响,但受声明环境影响

   //全局下的this指向window
   console.log(this);
   let ws = {name:"ws"}
   let a = ()=>{
    console.log(this);
   }
   ws.lookThis =  a
   a() // window
   ws.lookThis() // window

!箭头函数的this不受调用者影响,普通函数的this不受定义环境的影响。反之亦然