JS中This指向问题
汤姆不是猫 ... 2021-09-24 大约 1 分钟
众所周知,JS是个神奇的语言,往往都是出其不意~
下面聊一下JS中This指向的问题
# 场景1:函数直接调用
对于直接调⽤的函数,不管函数放在了什么地⽅,this指向为window
function test() {
console.log(this.user); // undefined
console.log(this); // window
}
test();
1
2
3
4
5
2
3
4
5
# 场景2:函数被调用
对于被调用的函数,被谁点出来的,this就是谁
场景1中的函数等价于window.test(),其实也是被window对象点出来的
function test() {
console.log(this) // => 对象obj
}
var obj = {
test: test
};
obj.test();
1
2
3
4
5
6
7
2
3
4
5
6
7
# 场景3:构造函数
在构造函数中,出现this.x = x中的this指向为当前类的实例
function test(name) {
this.name = name;
console.log(this); // => 实例a
}
var a = new test('汤姆不是猫');
1
2
3
4
5
2
3
4
5
# 场景4: apply、call、bind
call、apply:this是第⼀个参数
bind优于call/apply,call参数多,apply参数少
function getName(name) {
this.name = name;
console.log(this);
}
function Cat(name, color){
this.color = color; // => 实例Cat
getName.call(this, name); // => 原getName => 实例Cat
}
var cat = new Cat('汤姆', '蓝色');
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 场景5:箭头函数
箭头函数没有⾃⼰的this,看外层是否有函数
如果有:外层函数的this就是箭头函数的this指向
如没有:则this是window
var a = {
test: function() {
setTimeout(() => {
console.log(this); // => a
}, 0)
}
};
a.test();
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8