this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
function Cat(){
console.log(this)
this.miaomiao = function(){
console.log(this)
}
}
let Dog = () =>{
console.log(this)
}
let cat1 = new Cat() // Cat{} : 其实就是实例化出的cat1对象,这个时候没有miaomiao的方法
cat1.miaomiao(); // Cat{} : 其实就是实例化出的cat1对象,这个时候有miaomiao的方法
Cat(); // window ; 普通函数调用this指向的即为window,相当于隐式的全局变量吧
Dog(); // window :箭头函数的函数体中没有this,所以this的指向是其运行时所在的环境
function fn()
{
this.user = '追梦子';
return 1;
}
var a = new fn;
console.log(a.user); //追梦子
function fn()
{
this.user = '追梦子';
return {};
}
var a = new fn;
console.log(a.user); //undefined
如果返回值是一个对象,那么this指向的就是那个返回的对象,如果返回值不是一个对象包括null那么this还是指向函数的实例。
1.在严格版中的默认的this不再是window,而是undefined。
2.new操作符会改变函数this的指向问题,虽然我们上面讲解过了,但是并没有深入的讨论这个问题,网上也很少说,所以在这里有必要说一下。
会改变this指向的操作:
1、new
2、bind
3、call
4、apply