<script>
/* 箭头函数 与 function函数唯一的区别: this规则不同
1. function函数this指向有三种情况
this: 谁调用我,我就指向谁
(1)普通函数: 函数名() this指向window
(2)对象方法: 对象.方法名() this指向对象
(3)构造函数: new 函数名() this指向new创建的实例对象
2. 箭头函数this指向 : 箭头函数没有this
* 箭头函数中使用this,会访问上级作用域this
* 原因(作用域链):箭头函数没有this, 就会往上级作用域找
*/
let obj = {
name:'张三',
age:20,
eat:function(){
//eat是function函数, eat里面的this指向obj
let fn1 = function(){
//fn1是function函数, this指向window (普通函数调用)
console.log( this )//window
}
fn1()
let fn2 = ()=>{
//fn2是箭头函数, 访问上级作用域(eat函数)中的this
console.log( this )//obj
}
fn2()
},
learn:()=>{
//learn是箭头函数,this指向上级(全局)中的this:window
let fn1 = function(){
//fn1是function函数, this指向window (普通函数调用)
console.log( this )//window
}
fn1()
let fn2 = ()=>{
//fn2是箭头函数,访问上级作用域(learn)this : window
console.log( this )//window
}
fn2()
}
}
obj.eat()
obj.learn()
</script>