什么是this?
this --> 关键字;在JS中有特殊的含义。
注意: this 不能放到等号的左边;
下面看一下在不同的情景下,this不同的指向情况
1. 在全局作用域,this指向window;this 和window是同一块空间地址;
//直接在html文件中输出this,指向的window
console.log(this);// window
//下面这两个含义是一样的
window.alert()
this.alert();
2. 给元素的事件绑定的函数中的this,指向了当前被点击的那个元素;
<div id="box">点我</div>
<div id="box1">点我1</div>
<script>
box.onclick = function(){
//这里面的this : 是个对象;
console.dir(this===box); // 空间地址相同;
box.style.color="red";//给文字改变颜色
this.style.color="red";
//this=100;// this 不能放到等号的左边;
}
</script>
3.看函数执行前有没有".",如果要是没有,那么函数中的this指向window,如果有"." ,那么点前面是谁,this就指向谁;
var obj = {
m:1,
fn:function(){
console.log(this);
}
}
var f = obj.fn;
console.log(f==obj.fn);//true
obj.fn();//this==>obj
f();//this==>window
4. 自执行函数中this 永远指向window;
(function(){
console.log(this);// window
})();
var obj = {
fn:(function(){
console.log(this);// window
return function(){
console.log(this); // window
}
})()
}
var f= obj.fn;
f();
5. 回调函数中的this一般都指向window;
setTimeout(function(){
console.log(this);//window
},1000);
var ary=[1,2,3,4]
ary.map(function(){
console.log(this);//会输出4个window
})