Node.js this.varaiable 分配在 VS Code 中不起作用 [重复]

Node.js this.varaiable assignment not working in VS Code [duplicate]

提问人:joren 提问时间:1/20/2023 最后编辑:Sebastian Simonjoren 更新时间:1/20/2023 访问量:47

问:

如果我在其他地方运行它,则在 Node.js 代码下方运行它效果很好,但在 VS Code 中它会抛出错误。

    this.k= 8             
    TypeError: Cannot set properties of undefined (setting 'k')
    at subfun (file:///c:/Users/Administrator/Documents/2.js:3:15)
    at mainfun (file:///c:/Users/Administrator/Documents/2.js:6:5)
    at file:///c:/Users/Administrator/Documents/2.js:8:1
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:530:24)
    at async loadESM (node:internal/process/esm_loader:91:5)
    at async handleMainPromise (node:internal/modules/run_main:65:12)

我的代码:

var mainfun = function (){
    function subfun(a){
        this.k= 8
        console.log(this.k)
    }
    subfun()
}
mainfun()

需要上述解决方案才能在 VS Code 上运行,我正在寻找错误原因。

javascript node.js 函数 this

评论

0赞 Tamir Abutbul 1/20/2023
您很可能处于严格模式,这就是您收到错误的原因。在非严格模式下,k 将被创建为全局变量,但在严格模式下,您将收到一个错误。您的代码确实会运行。
0赞 joren 1/20/2023
@TamirAbutbul如何在非严格模式下运行??
0赞 Sebastian Simon 1/20/2023
@joren 启用后,无法禁用严格模式。无论如何,这是一个错误的问题。 在此上下文中是不正确的代码,严格模式会促使您编写更正确的代码。应该指什么?为什么你认为你需要在这里使用?this.k = 8thisthis
0赞 KooiInc 1/20/2023
实际上 subfun 是一个构造函数。查看此 stackblitz 代码段,了解如何使用它。
0赞 joren 1/20/2023
@SebastianSimon我的情况和我使用的代码的条件.我认为这也没有错。至少让我知道即使是新项目如何禁用严格模式?

答: 暂无答案