JavaScript this指向总结
在JavaScript中this永远指向当前函数的主人,即函数的调用对象或事件的调用对象,大致分为以下几种情况。
- 单独的this或者全局函数中的this指向window对象
console.log(this);//this => window对象
function fn1() {
console.log(this);//this => window对象
}
注:在es5严格模式下,this禁止指向window,会报错
- 对象的方法中,this指向调用当前方法的对象
var person = {
username: "钢铁侠",
show: function(){
alert("我的名字叫" + person.username);
alert("我的名字叫" + this.username); //this <==> person
}
}
person.show();//this => person对象
var a = person.show();
a(); //this => window对象
上面代码中person.show()由person对象调用,指向person对象,a()是把show方法
重新赋值给a,挂在window对象下面,所以指向window对象。
- 构造函数中this指向构造函数构造出来的对象
function Person() {
//this = new Object();//构造对象时,this指向构造出来的对象
this.a = 10;
//return this;
Person.prototype.show = function () {
console.log(this.age);//this => 构造出来的对象
}
var a1 = new Person();
a1.show(); //this => a1,打印10
- 事件绑定中,事件触发的函数中this指向当前绑定的事件
var btn = document.getElementById("btn1");
btn.onclick = function(){
console.log(this);//this => btn这个点击按钮
};
- 定时器中this指向window对象
setInterval(function () {
console.log(this);//this => window对象
},2000);
- 箭头函数中没有this,会默认继承上一次this的指向
var show = () => {
console.log(this);
}
show();//this => window对象
注:上面箭头函数show()的上一级为window,指向window对象
- 强制改变this指向的方法 call(), apply(), bind()
function show(a,b) {
console.log(this);
console.log(a,b);
}
show(1,2);//this => window对象
show.call('call',1,2);//this => 字符串call
show.apply('apply',[1,2]);//this => 字符串apply
show.bind('bind')(1,2);//this => 字符串bind
call,apply,bind方法都会强制将this指向第一个参数,上述方法作用都是相同的。
call方法第二个参数起为传递的参数,返回函数调用的结果。
apply方法只有两个参数,第二个参数为数组,包含传递的参数,返回同call。
bind方法只有一个参数,即指向的值,返回改变指向后的函数,所以在后面再调用一次
函数,把参数传递进去。