gpt4 book ai didi

javascript - `this` 绑定(bind)和 `this` 的调用站点

转载 作者:行者123 更新时间:2023-11-30 06:12:46 27 4
gpt4 key购买 nike

函数是否可以访问其调用站点中的所有信息?

我认为也许一个函数可以访问其调用站点范围,否则我可能会弄错,所以我希望得到反馈和解释。

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吗?

最佳答案

thisfoo()指的是调用它的上下文,在片段中它是在没有变量 a 的全局上下文中调用的在里面定义所以你得到undefined .

你还声明了a使用 let这会创建一个 block 范围的变量。如果你声明 a在函数外使用 var它会在全局范围内创建一个变量。

在我的代码片段中,我创建了一个具有两个属性的对象 afoo方法。现在,如果您调用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com