js this指向

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值