一.this的使用场景
1、纯粹的函数调用,这时this 就代表全局对象 window
function fn(){
this.x = 1;
console.log(this.x);
}
fn(); // 1
2、作为对象方法的调用,这时 this 就指这个上级对象
function test(){
console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1 this指向o这个对象
3、作为构造函数调用,这时this 就指这个新对象
function test(){
this.x = 1;
}
var o = new test();
console.log(o.x); // 1
二、改变this指向 call和apply
1.call,这时this指向call里面传的对象
function identify() {
return this.name.toUpperCase();
}
var me = {
name: "Kyle"
};
var you = {
name: "Reader"
};
identify.call( me ); // Kyle
identify.call( you ); // Reader
2.apply() 是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此this 指的就是这第一个参数。
var x = 0;
function test() {
console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m.apply(); //0
3.箭头函数,它没有自己的 this,当在内部使用了 this时,它会指向最近一层作用域内的 this
var obj = {
name: 'lyh',
sayName: function(){
return () => {
console.log('name:', this.name);
}
}
}
obj.sayName()() //name:lyh
总原则:this 总会指向,调用函数的那个对象。