this指向问题详解
js中的this指向问题是经常遇到并且面试时候经常问的,所以小编在这里列举了大家常见的几种this指向情况,希望能够为在前端路上奋勇前行的码友提供一些帮助(若在文章中出现些许需要改正的地方,还请码友及时联系小编加以纠正)
情况列举如下
this对象:a.自定义函数中的this对象指向window
b.事件处理程序中的this对象指向当前源事件
c. 对象中的方法里面的函数的this对象,谁调用这个方法,this就指向谁;
d.自执行函数中的this对象指向window
e.闭包中的this指向问题
注:在使用call()或者apply()方法改变函数执行环境的情况下,this就会指向其他对象
a.自定义函数中的this对象
<script type="text/javascript">
//1.在全局作用域中,this指向window
var a = 10;
console.log(this.a);//输出10
//2.在自定义函数中,this指向window
function fn(){
var b = 8;
var a = 9;
console.log(this.b);//undefined
console.log(this.a);//输出10
}
fn();
function fn1(){
var a = 1;
fn(); //此时在fn1中调用fn,输出的结果与在全局作用域中调用fn一致,说明此时this还是指向window
}
fn1();
</script>
b.事件处理程序中的this对象指向当前源事件
*隐藏
这是一个div
<script type="text/javascript">
var a = document.getElementById("do");
var box = document.getElementById("box");
var change = true;
a.onclick = function(){
change = !change;
if(change){
box.style.display = "none";
a.innerHTML = "显示";
}else{
box.style.display = "block";
a.innerHTML = "隐藏";
}
console.log(this); //此时this指向调用这个方法的button,输出的是button结构
}
</script>
对象中的方法里面的函数的this对象,谁调用这个方法,this就指向谁;
function Person(name,age,height){
this.name = name;
this.age = age;
this.height = height;
this.testHeight = testHeight;
}
function testHeight(){
console.log(this.height);
console.log(this);
}
var person1 = new Person("tom",23,178);//此时person对象调用了testHeight函数,this指向person对象;即使它被定义在全局作用域中
person1.testHeight();
这里的testHeight()方法被person对象调用,输出的this也是指向person对象
自执行函数中的this对象指向window
(function(){
console.log(this);//这里输出window对象
})()
这里的this指向window对象
闭包中的this指向问题
在一般情况下,闭包中的this指向和在全局作用域中定义的函数指向的一样,都是window对象,
但在有些情况下,闭包中的this指向有时候会得出惊人意料的结果,例如下面的例子:
var name = "wei";
var obj = {
name : "tom",
fun : function(){
return function(){
console.log(this.name);//输出name为wei,
console.log(this);//输出this对象为window,
}
}
}
obj.fun()();//此时的this指向window
//此时即使在对象中调用函数,this还是指向window对象
var name = "wei";
var obj = {
name : "tom",
fun : function(){
var that = this;//这里用一个变量that保存了this
return function(){
console.log(that.name);//输出tom
console.log(that);//这里输出object对象
}
}
}
obj.fun()();//此时的保存的this对象的that指向object;
说明:在将this赋值给其他变量时,this的指向并不能出现像以上规则一样的结果,而是会保存
被this赋值的变量(就比如上面例子的that)的作用域指向