gpt4 book ai didi

javascript - 使用 this.str 时变量未定义

转载 作者:行者123 更新时间:2023-12-03 00:55:53 27 4
gpt4 key购买 nike

我这里有一些简单的代码,正在 Visual Studio Code 中使用 Quokka 和 NodeJS 运行。

var str = "hello"

function printStr(){
console.log(this.str);
}

printStr();

输出:

undefined​​​​​ at ​​​this.str​​​ ​quokka.js:6:4​

我可以在我的网络浏览器中很好地运行这段代码,并且它工作得很好,打印出“hello”。

“使用严格”;未启用

截图:/image/uCGLf.png

最佳答案

在浏览器中,this 将被解释为窗口对象,并且变量 str 将在窗口上定义。 Node.js 中没有 window 对象。目前尚不清楚为什么您在这里使用 this 而不是使用常规范围规则。这在浏览器和 Node 中都有效:

var str = "hello"

function printStr(){
console.log(str); // will see outside scope
}

printStr();

更好的是,将值传递到函数中,这样它就不会依赖于在其范围之外定义的值:

var str = "hello"

function printStr(s){
console.log(s);
}

printStr(str);

在 Node 中有一个 global 对象,它与浏览器的 window 对象有一些相似之处,所以像这样的代码可以在 Node 中工作,但这将是一种相当非标准的方法:

global.str = "hello"

function printStr(){
console.log(this.str)
}

printStr();

关于javascript - 使用 this.str 时变量未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52841597/

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