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

标签 javascript object binding this

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

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

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/

相关文章:

javascript - 如何在 LoopBack 2.0 中隐藏 REST API 方法?

java - Java 代码中 JRuby 对象的序列化

java - getLastNonConfigurationInstance 总是返回 null

Javascript:如何迭代对象 [键:值] 但跳过一些键([可能的最快方式])

c# - 在 wpf 中重置绑定(bind)的源

c# - 绑定(bind) List<string> 到 ComboBox

ios - SwiftUI 动画不会在绑定(bind)更新时发生

javascript - 如何访问具有 ul 和 id 的标签的 href

javascript - 导入的数据库函数未在 Expressjs 中返回路由内的值

javascript - 使用 hrefs 使用 jquery 构建选择表单