项目场景:
this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。
我们要做的就是找出该函数是属于哪个对象的
或者是哪个对象调用该函数的
先看如下代码
let a = {
b : function(){
let func = function(){
console.log(this)
this.alert("哈哈")
console.log(this.c);//undefined
}
func();
},
c : 'Hello!'
}
a.b();
问题描述
console.log(this.c)打印结果是undefined
this竟然指向了window对象
原因分析:
函数b的内部函数func其实是属于window对象的
可以将函数修改为如下代码
let a = {
b : function(){
window.func = function(){
this.alert("哈哈")
console.log(this.c);
}
window.func()
},
c : 'Hello!'
}
a.b();
解决方案:
可以通过bind来改变this指向,
let a = {
b : function(){
let func = function(){
console.log(this.c);
}
func.bind(this)()
},
c : 'Hello!'
}
a.b();
此时this指向a对象