JS中的this

JS中的this

如何确定this的值

1.在全局执行环境

在全局执行环境中,严格模式和非严格模式,this都指向全局对象,浏览器中指向Window。

1
2
3
4
console.log(this);  //-->Window

'use strict'
console.log(this); //-->Window

2.在函数内部

2.1直接调用

在函数内部直接调用,非严格模式下,this指向全局对象Window。

在函数内部直接调用,严格模式下,this指向undefined。

1
2
3
4
5
6
7
8
9
10
function func(){
console.log(this);
}
func() //-->Window

'use strict'
function func2(){
console.log(this);
}
func2() //-->undefined
2.2对象方法调用

在函数内部用对象方法调用,严格模式和非严格模式下都指向调用者本身。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const food = {
name: '烧鸭饭',
eat(){
console.log(this);
}
}
food.eat() //-->food

'use strict'
const food = {
name: '烧鸭饭',
eat(){
console.log(this);
}
}
food.eat() //-->food

总结

在全局执行环境中,严格模式和非严格模式,this指向Window。在函数内部直接调用,非严格模式this指向Window,严格模式this指向undefined,使用函数内部对象调用方式,严格模式和非严格模式都指向调用者。

如何指定this的值

可以通过两类方法指定this:

1.调用时指定

1.1call方法

call方法挨个传入参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function func(numA,numB){

console.log(this);

console.log(numA,numB);

}

const Person ={

name:'along'

}

func.call(Person,1,2) //-->Person对象 1,2

this指向通过call方法改变成Person。

1.2apply方法

apply方法,按数组传入参数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function func(numA,numB){

console.log(this);

console.log(numA,numB);

}

const Person ={

name:'along'

}

func.apply(Person,[1,2]) //-->Person对象 1,2

apply方法除了传参用数组传参,其余与call一样。

2创建时指定

2.1bind方法

bind()方法主要就是将函数绑定到某个对象,bind()会创建一个函数,函数体内的this对象的值会被绑定到传入bind()第一个参数的值,当然这是绑定,不是像call、apply一样直接执行,apply要执行的话还得自己调用。

1
2
3
4
5
6
7
8
9
function func(numA,numB){
console.log(this);
console.log(numA,numB);
}
const Person ={
name:'along'
}
const bindFunc = func.bind(Person,1) //此时this变为Person并传入1
bondFunc(2) //再传入一个参数numB2 -->Person对象 1,2
2.2箭头函数
1
2
3
4
5
6
7
8
9
10
11
12
13
const food ={
name:"烧鸭饭",
eat(){
console.log(this);
setTimeout(function(){
console.log(this);
},1000);
setTimeout(()=>{
console.log(this);
},2000)
}
}
food.eat() //-->food Window food

第一个console.log(this)打印的是调用者food,第二个打印的是全局对象Window,打三个箭头函数打印的是上一级的this,所以是food。


JS中的this
http://example.com/2023/09/07/JS中的this/
作者
AlongSunsea
发布于
2023年9月7日
许可协议