this指向

92 阅读1分钟

this指向

1.this定义:this就是一个变量,它的值是一个对象,是程序运行时内部自动生成的,代表着当前的运行环境。

2.this的指向

(1)在全局环境中,this指向的是window

console.log(this)

(2)普通函数调用的时候,this指向window

function fn (){ console.log(this) } fn()

(3)在定时器中,this指向的是window

setInterval(function(){ console.log(this) },1000)

(4)函数作为对象的方法使用时,谁调用,fn内部的this就指向谁

const obj = { name:“小明”, fn:function(){ console.log(this) } } obj.fn()

3.this 的指向,在定义的时候是不能确定的,只有在调用执行的时候,才能确定他的指向

(1)obj.fn ()

this 指向的是obj

(2)先取出函数,再调用执行,这时this指向的是window

let foo = obj.fn foo()

(3)事件绑定的时候,this指向被绑定的函数

const btn = document.querySelector('button')

btn.addEventListener('click',function(e){

console.log(this)

console.log(e.target)

console.log(e.currentTarget)

})

(4)构造函数中的this指向的是他创建的实例

function Foo(name,age){

this.name = name

this.age = age

console.log(this)

}

const p1 = new Foo('小红',13)

const p2 = new Foo('小花',14)