首页 > 解决方案 > 为什么 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',
        .....
        .....
        .....

标签: node.js

解决方案


在编写自调用异步函数之前,您总是需要放置一个分号。代码将像这样工作:

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

推荐阅读