gpt4 book ai didi

node.js - 为什么在函数内部调用时 this 指向应用程序进程?

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:17 25 4
gpt4 key购买 nike

在我的 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 () => {
...
...
...
})()

关于node.js - 为什么在函数内部调用时 this 指向应用程序进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150679/

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