函数是否可以访问其调用站点中的所有信息?
我认为也许一个函数可以访问其调用站点范围,否则我可能会弄错,所以我希望得到反馈和解释。
function bar() {
// call-stack is: `bar`
// so, our call-site is in the global scope
let a = “heyo”;
console.log( “bar” );
foo(); // ← call-site for `foo`
}
function foo() {
// call-stack is: `bar` -> `foo`
// so, our call-site is in `bar`
console.log( “foo “ + this.a );
}
bar(); // ← call-site for `bar`
这里,this.a返回undefined,但是如果它的调用点是声明a
的地方,难道它不应该访问变量a
吗?
最佳答案
this
在 foo()
指的是调用它的上下文,在片段中它是在没有变量 a
的全局上下文中调用的在里面定义所以你得到undefined
.
你还声明了a
使用 let
这会创建一个 block 范围的变量。如果你声明 a
在函数外使用 var
它会在全局范围内创建一个变量。
在我的代码片段中,我创建了一个具有两个属性的对象 a
和 foo
方法。现在,如果您调用 obj.foo()
obj
上下文中的方法this
将指向 obj
对象,因为我声明了 a
使用 var
在全局调用 foo()
将打印 a
的值来自全局范围:
var a = "from global";
function bar() {
//lexical context is global
//let defines a variable in the enclosing scope
let a = "heyo";
console.log( "bar" );
//foo is called within the global context, so this points to global object.
foo();
let obj = {a : "from obj", foo};
// or foo.bind(obj); which sets the this context
//now foo is called in the context of object "obj" so this points to obj
obj.foo();
}
function foo() {
console.log( "foo " + this.a );
}
bar();
关于javascript - `this` 绑定(bind)和 `this` 的调用站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929672/