小编Ign*_*ías的帖子

类中嵌套函数之间的对象上下文(“this”)

希望你们都做得很好。

我有一个关于对象的上下文如何在 Node.JS(或一般的 JS)函数上工作的问题。我理解“当您在 Javascript 中调用顶级函数时,函数内的 this 关键字指的是默认对象”。例如,我有以下功能:

function nestedFunctions() {
    var a = "I am a variable"
    console.log("Initial context:")
    console.log(this)
 
    function one() {
        console.log("First nested function, this is my this context:")
        console.log(this)
        console.log("First nested function, this is my a value:")
        console.log(a)
 
        function two() {
            console.log("Second nested function, this is my this context:")
            console.log(this)
            console.log("Second nested function, this is my a value:")
            console.log(a)
        }
        two()
    }
    one()
}
nestedFunctions()
Run Code Online (Sandbox Code Playgroud)

给出以下输出:

Initial context:
Object Global
First nested function, this …
Run Code Online (Sandbox Code Playgroud)

javascript node.js

5
推荐指数
1
解决办法
65
查看次数

标签 统计

javascript ×1

node.js ×1