function函数
1 function Person(){ 2 this.name = 'Jack', 3 this.age = 25, 4 this.sayName = function(){ 5 console.log(this.name) 6 function inner(){ 7 console.log(this.name) 8 console.log(this) 9 } 10 inner() 11 } 12} 13let x = new Person() 14x.sayName()
Output

在这里, this.sayName() 中的 this.name 是可访问的,因为 this.sayName() 是一个对象的方法。
但是,inner() 是一个普通函数, this.name 不可访问,因为 this 指的是全局对象(浏览器中的 Window 对象)。 因此,inner() 函数中的 this.name 给出了 undefined。
箭头函数
1function Person() { 2 this.name = 'Jack', 3 this.age = 25, 4 this.sayName = function () { 5 6 console.log(this.age); 7 let innerFunc = () => { 8 console.log(this.age); 9 } 10 11 innerFunc(); 12 } 13} 14 15const x = new Person(); 16x.sayName();
Output

这里,innerFunc() 函数是使用箭头函数定义的。 在箭头函数内部, this 指的是父级的作用域。 因此, this.age 给出 25。
