1.普通函数中this是在函数运行时才会确定this的指向
2.普通函数中的箭头函数中的this是在函数运行后,到了箭头函数定义处,产生箭头函数,才会确定this的指向
第一句话的解释:
var a = 11
function test1() {
this.a = 22;
return function () {
console.log(this.a);
}
}
var x = new test1()(); // this是指向window的
// 输出11
第二句话的解释:
var a = 11
function test1() {
this.a = 22;
return ()=>{
console.log(this.a);
}
}
var x = new test1()(); //new的时候开始执行test1函数中的方法,此时this指向的是实例x,运行到箭头函数处,开始确定箭头函数中的this指向,此时箭头函数中的this就指向实例x。
//输出22
3.对象中的普通函数,这个函数是谁调用的,this就指向谁
var name='我是全局'
var obj={
name:"我是obj",
func:function(){
console.log(this.name)
}
}
obj.func()
// 输出 我是obj
4.对象中的箭头函数,指向定义箭头函数时其父级作用域
var name='我是全局'
var name='我是全局'
var obj={
name:"我是obj",
func:()=>{
console.log(this.name)
}
}
obj.func() //对象中箭头函数是在obj中定义,用一个属性接收,obj的父级this就是window。
// 输出 我是全局
普通函数和箭头函数中this的指向
最新推荐文章于 2022-07-29 18:05:45 发布