JS-this指向问题

104 阅读1分钟

this指向window

直接调用方法

function foo(){
    console.log(this)
}
foo()//window

直接调用方法内部的方法


function foo(){
    function foo1()
    {
        console.log(this) 
    }
    return foo1//闭包的写法,将内部的方法保存出来
}
let fun = foo()//保存内部的foo1 
fun()//打印window

普通方法内有箭头函数

const demo = (function(){
    return ()=>{
        console.log(this)
    }
}())
demo()

分析:

  1. 看后半部分为立即执行函数,说明,刚进该函数,this指向window;
  2. 由于箭头函数中的this只和代码结构有关,内部this就是当前环境中的this,指向window

直接使用立即执行函数

(function(){
    console.log(this)
}())//打印window

this指向构造函数

使用new方法创建一个对象,内部的this被改变指向构造函数

function Demo(){
    console.log(this)
}
let demo1 = new Demo()//Demo {},这里一定要用new

在构造函数里使用箭头函数来给属性赋值

function Demo(){
    this.fun = ()=>{
        console.log(this)
    }
}
let demo1 = new Demo()
demo1.fun()//Demo {},这里一定要用new

分析:

  1. new方法进入构造函数,this指向构造函数;
  2. 由于箭头函数中的this只和代码结构有关,内部this就是当前环境中的this,指向构造函数

this指向对象

通过自变量的方式可以实现

let obj = {
    name : "qwer",
    fun(){
        console.log(this)//内部函数的this指向就是对象本身
    }
}
obj.fun()//{name: "qwer", fun: ƒ}

字面量生成的对象内部的箭头函数不可能指向对象本身,因为字面量对象内部不形成新的作用域,箭头函数直接指向对象所在的作用域

let obj = {
    name : "qwer",
    fun:()=>{
        console.log(this)//内部函数的this指向就是对象本身
    }
}
obj.fun()//Window

练习

let obj = (function(){
    return {
        cont:0,
        counter:()=>{
            console.log(this)
            this.cont++;
            console.log(this.cont)
        }
    }
}())
obj.counter()//this为window,this.cont为NaN。this.cont本为undefined,运算++后,变成NaN