概括
首先,this 的指向在函数定义的时候是确定不了的,只有在函数调用的时候才能确定 this 到底指向谁。概括来说就是 this 指向调用它的对象。(ES6 中的箭头函数例外,箭头函数中没有 this,因此箭头函数内部的 this 实际上就是它所在的环境中的 this) 。
举例说明
//函数直接调用时
window.name = 'Global';
function sayName() {
return this.name;
}
console.log(sayName());//Global
var count = {
name:'count',
timer:function () {
setTimeout(function () {
console.log( this.name );//GLobal
},1000);
}
};
count.timer();
//函数作为对象的方法调用时
var obj = {
name:'obj',
sayName:sayName
}
console.log(obj.sayName());//obj
//通过call,apply调用函数时
var car = {
name:'法拉利'
};
console.log(obj.sayName.call(car));//法拉利
//构造函数调用时
function Cat(name,age) {
this.name = name;
this.age = age;
}
var cat1 = new Cat('叮当',2);//this 指向新创建的实例
//ES6 箭头函数中的 this
window.name = 'Global';
const fun = function(){
setTimeout( function(){
console.log(this.name)
},1000)
}
const funArrow = function(){
setTimeout( () => console.log(this.name),1000);
}
fun.call({name:'call'});//Global
funArrow.call({name:'call'});//call