箭头函数和普通函数他们在 对象、构造函数、构造函数.prototype.方法中他们的this 指向 该如何理解, 看了好多文章 有点学蒙了
本人目前总结
- 普通函数的this 指向window
- 构造函数中的this 指向实例本身 (不区分函数)
- 当函数做为对象的属性方法调用时候 this指向该对象
- 当箭头函数做为对象的属性方法调用时候 this指向该属性父级执行上下文中的this
- 箭头函数不能用于构造函数 会报错
- 构造函数使用prototype定义属性 使用箭头函数的时候 this 指向window
- 构造函数使用prototype定义属性 使用普通函数的时候 this 指向该实例
- 这是因为 箭头函数没有this, 他的this 是在定义的时候绑定, 父级执行上下文的this
- 函数中this 指向 离他最近的构造函数中的this, 普通函数的构造函数是function this 指向window 构造函数就是指向本身
let obj = {
name: '赤'
children: {
name: '橙',
asy: () => {
console.log(this.name)
}
}
}
function Persion() {
this.name = "黄"
this.hello = () => {
console.log(this)
}
open: function() {
console.log(this)
}
}
大佬 可以用这个题给我解释一下 这句话 箭头函数的 this 指向声明时的上下文 在这上边的用法嘛 感谢
就两句:
this
指向调用者this
指向声明时的上下文