【发布时间】:2019-03-21 05:26:46
【问题描述】:
在 ExpressJS 设置中,我有 server.js,我在其中执行以下操作:
import { call_method } from '../hereIam.mjs';
const process_db = async () => {
console.log(this); // undefined
call_method(this);
};
console.log(this) // undefined
process_db();
然后,我想从hereIam.mjs 调用父方法,但这是未定义的
export const call_method = parent_this => console.log(parent_this); // undefined
我试图在 server.js 中包含类,以试图强制拥有 this
class AppServer {
constructor() {
console.log(this)
}
const process_db = async () => call_method(this);
}
但似乎类中的箭头函数无法在(实验性)NodeJS中编译(这应该是另一个问题)
已编辑
我如何做到这一点是避免使用箭头符号以便能够在 Express 中使用类,然后实例化一个提供 this 的类。
class AppServer {
async process_db() {call_method(this)};
}
let server = new AppServer();
server.process_db();
问题是,获得this 引用的唯一方法是使用对象/类?
【问题讨论】:
-
不,在讨论箭头之前这是未定义的。我现在正在编辑问题
-
记住,作用域是在你使用
new关键字时创建的 -
哦,谢谢,这是关于新的,谢谢!
-
是的,您需要函数或类才能拥有 this 对象。 Lambda 函数使用其外部作用域。所以它将在其外部范围内使用它。
标签: javascript node.js express this