javascript - 使用 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
我可以在我的网络浏览器中正常运行这段代码,它工作得很好,打印出“你好”。
“使用严格”;未启用
解决方案
在这种情况下,在浏览器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();
推荐阅读
- sql - 合并语句给我“无法获得一组稳定的行”错误
- ms-access - 用于将条目与表匹配的访问表达式/VBA
- c# - 每天在特定时间显示 Windows Toast
- html - 带有 Html CSS 的多级导航栏
- javascript - 如何在通用验证器类 angular2 中实现自定义验证器?
- vba - 将工作表 1 的最后一行复制到工作表 2 上的行数
- java - 为什么从 Android Studio 3.1.3 的调色板中移动组件后我的布局显示为空白?
- liferay - 创建新的 liferay 门户实例时出错
- c# - 比较日期适用于一台机器但不适用于另一台机器
- python - pandas - 'dataframe' 对象没有属性 'str'