首页 > 解决方案 > 使用 this.str 时变量未定义

问题描述

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

var str = "hello"

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

printStr();

输出:

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

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

“使用严格”;未启用

截图:https ://i.imgur.com/IEQwv5D.png

标签: javascriptnode.jsvisual-studio-code

解决方案


在这种情况下,在浏览器this中将被解释为窗口对象,并且变量str将在窗口上定义。Node 中没有窗口对象。目前尚不清楚您为什么this在这里使用而不是使用常规范围规则。这将在浏览器和节点中工作:

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();

推荐阅读