this指向
# this指向
# 全局执行上下文中的 this
全局执行上下文中的 this 是指向 window 对象的。这也是 this 和作用域链的唯一交点,作用域链的最底端包含了 window 对象,全局执行上下文中的 this 也是指向 window 对象。
# 函数执行上下文中的 this
function foo(){
console.log(this)
}
foo()
1
2
3
4
2
3
4
在 foo 函数内部打印出来 this 值,执行这段代码,打印出来的也是 window 对象,这说明在默认情况下调用一个函数,其执行上下文中的 this 也是指向 window 对象的。那能不能设置执行上下文中的 this 来指向其他对象呢?通常情况下,有下面三种方式来设置函数执行上下文中的 this 值。
# 1. 通过函数的 call ,apply,bind方法设置
let bar = {
myName : "极客邦",
test1 : 1
}
function foo(){
this.myName = "极客时间"
}
foo.call(bar)
console.log(bar)
console.log(myName)
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 2. 通过对象调用方法设置
var myObj = {
name : "极客时间",
showThis: function(){
console.log(this)
}
}
myObj.showThis()
1
2
3
4
5
6
7
2
3
4
5
6
7
使用对象来调用其内部的一个方法,该方法的 this 是指向对象本身的。
稍微改变下调用方式,把 showThis 赋给一个全局对象,然后再调用该对象,代码如下所示:
var myObj = {
name : "极客时间",
showThis: function(){
this.name = "极客邦"
console.log(this)
}
}
var foo = myObj.showThis
foo()
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
this 又指向了全局 window 对象
所以通过以上两个例子的对比,你可以得出下面这样两个结论:
- 在全局环境中调用一个函数,函数内部的 this 指向的是全局变量 window。
- 通过一个对象来调用其内部的一个方法,该方法的执行上下文中的 this 指向对象本身。
# 3. 通过构造函数中设置
function CreateObj(){
this.name = "极客时间"
}
var myObj = new CreateObj()
1
2
3
4
2
3
4
构造函数中的 this 其实就是新对象本身。
# this 的设计缺陷以及应对方案
# 1. 嵌套函数中的 this 不会从外层函数中继承
var myObj = {
name : "极客时间",
showThis: function(){
console.log(this) // myobj
function bar(){
console.log(this) // window
}
bar()
}
}
myObj.showThis()
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
函数 bar 中的 this 指向的是全局 window 对象,而函数 showThis 中的 this 指向的是 myObj
如何解决这个问题:
- 声明一个变量 self 用来保存 this
var myObj = {
name : "极客时间",
showThis: function(){
console.log(this)
var self = this
function bar(){
self.name = "极客邦"
}
bar()
}
}
myObj.showThis()
console.log(myObj.name)
console.log(window.name)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 改为箭头函数
var myObj = {
name : "极客时间",
showThis: function(){
console.log(this)
var bar = ()=>{
this.name = "极客邦"
console.log(this)
}
bar()
}
}
myObj.showThis()
console.log(myObj.name)
console.log(window.name)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
ES6 中的箭头函数并不会创建其自身的执行上下文,所以箭头函数中的 this 取决于它的外部函数
编辑 (opens new window)
上次更新: 2022/05/22, 18:34:11