废话不多说,先贴代码
let obj = {
func: say
}
function say() {
let word = 'Shit This'
console.log(this);
console.log(word);
// function person() {
// console.log(this); // window
// }
let name = () => {
console.log(this); // {func: ƒ}
}
return name
}
obj.func()() //剪头函数主要解决 this 不能被继承的问题
在上面的代码中,如果return 返回到是person
let obj = {
func: say
}
function say() {
let word = 'Shit This'
console.log(this);
console.log(word);
function person() {
console.log(this); // window
}
// let name = () => {
// console.log(this); // {func: ƒ}
// }
return person
}
obj.func()() //剪头函数主要解决 this 不能被继承的问题
那么person中的this指向的是window , 个人猜测在普通函数中,this的指向是其父级作用域. 而 obj.func()() 说明 作为函数被返回到person 并在 window 中执行 ,那么 person 的this 就指向的就是window. 箭头函数是没有自身的this的,它的this 指向的是其父级作用域所指向的对象
name 作为函数被返回,结果this指向了 obj
说明 this在声明阶段就已经完成了this的确认,而普通函数只有在执行阶段才会确认this的指向