[英]Accessing JS Class/Object Variables Via Instance Methods and This - Execution Contexts
First Question: Why is the value for this
in getXArrow() equal to the Solution object? 第一个问题:为什么是值
this
在getXArrow()等于溶液对象? Shouldn't it equal the this
value of the solution object which called it, which would be the Window object? 它不应该等于解决方案对象的
this
值,该对象就是Window对象吗?
Second Question: Shouldn't the JS Engine travel up the scope chain of each function to find the value of x? 第二个问题:JS引擎是否不应该沿每个函数的作用域链向上求x的值? The scope of getX() and getXArrow() don't have
x
, so the JS engine would check their caller (the Solution object) and find x: 10
, as declared in the constructor. getX()和getXArrow()的范围没有
x
,因此JS引擎将检查其调用方(解决方案对象)并找到x: 10
,如构造函数中所声明的那样。 Instead, it seems to jump up to the global scope? 相反,它似乎跳到了全球范围?
let x = 5
class Solution {
constructor() {
this.x = 10
}
getX() {
console.log(this);
console.log(x);
}
getXArrow = () => {
console.log(this);
console.log(x);
}
}
s.getXArrow() // Output: Solution
// 5
s.getX() // Output: Solution
// 5
Thank you! 谢谢!
getX
just has two scopes accessible: It's own function scope and the global scope. getX
仅有两个可访问的作用域:它是自己的函数作用域和全局作用域。 Classes don't create a scope, and thus x
cannot be accessed. 类不会创建作用域,因此无法访问
x
。 You do however have access to the instance via this
and can access its .x
property. 但是,您确实可以通过
this
方法访问实例,并且可以访问其.x
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.