node.js - 为什么 this 在函数内部调用时指向应用程序进程?
问题描述
在我的 Node 应用程序中编写以下代码:
Date.prototype.getDayName = function() {
let daysOfWeek = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
return daysOfWeek[this.getDay()]
}
(async () => {
...
...
...
})()
我知道 this.getDay() 不是一个函数。当我在这个上下文中记录这个时,我得到了进程对象:
Object [global] {
global: [Circular],
process:
process {
title: 'node',
version: 'v10.12.0',
versions:
{ http_parser: '2.8.1',
node: '10.12.0',
v8: '6.8.275.32-node.35',
uv: '1.23.2',
zlib: '1.2.11',
ares: '1.14.0',
.....
.....
.....
解决方案
在编写自调用异步函数之前,您总是需要放置一个分号。代码将像这样工作:
Date.prototype.getDayName = function() {
let daysOfWeek = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
return daysOfWeek[this.getDay()]
}; //You need to put a semi-colon before writing a self calling async function
(async () => {
...
...
...
})()
推荐阅读
- javascript - 使用 react-router 的无效挂钩调用 useSelector()
- python - 在 Simulink 中调用具有多个输出的 Python 函数
- swift - 迁移以更改 CoreData 的配置
- elasticsearch - kibana 中可用的已解析数据的问题
- android - 每次使用具有不同 TextView 的适配器
- excel - 全局变量在用户表单后失去价值
- excel - 锁定单元格并用数据验证/VBA 替换内容
- c# - 在 C# 中过滤 XmlDocument xml 的最快方法
- wordpress - 批量更新所有描述类别
- php - 使用 php 中的隐藏字段 var 获取表单操作以启动类函数