Javascript 箭头功能范围与常规功能范围
我已经阅读了Javascript中箭头函数和常规函数之间的区别,因此我制作了一个小小的node.js演示项目来了解我学到的东西Javascript 箭头功能范围与常规功能范围,javascript,Javascript,我已经阅读了Javascript中箭头函数和常规函数之间的区别,因此我制作了一个小小的node.js演示项目来了解我学到的东西 let name = 'file Scope' class User { name = "Class Scope" arrow = () => { console.log("Arrow name " + this.name); } normal() { console.log("Normal name " +
let name = 'file Scope'
class User {
name = "Class Scope"
arrow = () => {
console.log("Arrow name " + this.name);
}
normal() {
console.log("Normal name " + this.name);
}
test() {
return {
name: "Object Scope",
n: this.normal,
a: this.arrow,
nested: {
name: 'Nested Object Scope',
nestedNormal: function () {
console.log("Nested Normal " + this.name);
},
nestedArrow: () => {
console.log("Nested Arrow " + this.name);
}
}
}
}
}
let user = new User();
user.test().n(); //Normal name Object Scope
user.test().a();//Arrow name Class Scope
user.test().nested.nestedNormal();//Nested Normal Nested Object Scope
user.test().nested.nestedArrow();//Nested Arrow Class Scope
控制台输出不是预期的,我认为nestedArrow()函数将返回对象范围,但它返回的是类范围
为什么“this.name”指的是类中的名称而不是嵌套对象内部的名称?箭头函数在
test()
函数中声明,因此它从该函数中获取this
的值
您调用了user.test()
,因此在test
中此
的值与用户
的值相同
user.name
是的“类范围”
进一步阅读:.
此
绑定到函数声明时的状态。您可以在user
实例的方法test()
中声明它。它需要这个-一般来说,在对象初始化器中使用此
时,不会指当前正在初始化的对象,而是指正在初始化对象的上下文。此外,您似乎混淆了“范围”和“上下文”。范围是如何查找变量,而上下文是this
的值。这两者没有联系。