首先,this只有在函数function中才需要去判断它的指向。如果是在全局环境中,this永远指向全局对象。浏览器环境中,全局对象为window对象,NodeJs环境中,全局对象为global对象。
普通函数中的this
普通函数中的this,永远指向window对象//普通函数
function foo() {
console.log(this); //指向window对象
}
foo();
对象方法中的this
对象方法中的this,指向调用该方法的对象。const student = {
name:'starnight',
sayName:function(){
console.log(this);
}
};
student.sayName();
事件中的this
事件中的this,指向绑定该事件的元素。const father = document.getElementById('father');
father.onclick = function(event){
console.log(this);
}
构造函数中的this
构造函数中的this,指向new调用时得到的实例对象。function Person(){
console.log(this);
}
Person.prototype.sayName = function(){
console.log(this);
}
const p = new Person();
const b = new Person();
箭头函数中使用this
ES6的箭头函数比较特殊,箭头函数中的this不需要按照上诉情况去进行判断。因为箭头函数没有自己的this,因此我们在箭头函数中访问this时,实际上访问的是父级(箭头函数创建时所在的范围)的this。const student = {
fpp:function(){
return () => {
console.log(this);
}
}
}
const bar = student.foo();
bar();
改变this的指向
改变this的指向有三种方法:call、apply、bind;call和apply都是在改变this指向的同时,立即执行该函数。
apply在传参时,传递数据需要以数组的形式进行传递,call不需要。
bind是在改变this指向后返回一个新的函数,需要再次调用来执行该函数。
const student = {
name:'starnight',
sayName:function(a,b){
console.log(this.name,a,b);
}
};
const person = {name:'list'};
person.sayName = student.sayName;
person.sayName.call(student,10,20);
person.sayName.apply(student,[10,20]);
person.sayName.bind(student)(10,20);