1、普通函数中this的指向
普通函数中this的指向,永远指向最后调用这个函数的对象。
例如:a.b.fn(),那么fn()函数中的this指向对象b。
2、构造函数中this的指向
一般来说,构造函数this的指向永远指向new关键字实例化的那个对象。
function Person(name){
this.name = name;
}
let p = new Person("xingyun");
console.log(p.name); // xingyun
如果构造函数返回一个对象,则使用new关键字实例化的对象指向构造函数返回的那个实例对象(null除外,虽然null是对象但不是实例)。同时this的指向也指向那个返回的对象。
function Fn(){
this.user = "xingyun";
this.date = new Date();
return {
user: "Rose",
};
}
let a = new Fn();
console.log(a.user); // Rose
console.log(a.date); // undefined
3、使用call、apply和bind可以改变this的指向。
4、箭头函数
箭头函数的this始终指向外部对象。因为箭头函数没有this,因此它自身不能进行new实例化,也不能使用call、apply和bind改变this指向。
5、严格模式
严格模式中,this的默认值是undefined,而不是window。