this是js中的一个关键字,相当于一个变量,在不同的地方有不同的值,这和this的指向有关
this不可以被赋值,如果赋值给this则会报错
this指向
1、全局作用域中 this 指向window
console.log(this) // window
2、函数直接调用 this 指向window
(开启严格模式时,指向undefined)
function fn(){
console.log(this) // window
}
fn()
3、事件的回调函数 this 指向事件源
document.addEventListener('click',function(){
console.log(this) // document
})
4、构造函数 this 指向实例化对象
function Person(age){
this.age = age
console.log(this) // {age:20}
}
const p1 = new Person(20)
5、定时器 this 指向window
setInterval(function(){
console.log(this) // window
})
6、IIFE this 指向window
;(function(){
console.log(this) // window
})()
7、谁调用函数,this就指向谁
let obj = {
age: 20,
f: function(){
console.log(this)
}
}
obj.f() // {age: 20, f: ƒ}
改变this指向
call()
改变指定函数的this指向,并执行函数
参数一:this需要指向的目标;后续参数,函数的参数
let obj = {age: 10}
function fn(x,y){
console.log(this)
console.log(x+y)
}
fn(1,2) // window 3
fn.call(obj,3,4) // {age: 10} 7
apply()
改变指定函数的this指向,并执行函数
参数一:this需要指向的目标;参数二:函数的参数组成的数组
let obj = {age: 10}
function fn(x,y){
console.log(this)
console.log(x+y)
}
fn(1,2) // window 3
fn.apply(obj,[3,4]) // {age: 10} 7
bind()
改变函数this指向,返回一个新函数(不会像call和apply一样立即调用函数)
参数一:this需要指向的目标;后续参数:函数的参数
let obj = {age: 10}
function fn(x,y){
console.log(this)
console.log(x+y)
}
const res = fn.bind(obj,3,4)
res() // {age: 10} 7