在 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
引用的唯一方法是使用对象/类?
最佳答案
您可以使用 bind方法并传递任何对象以用作 this
上下文。
但是,箭头函数从调用它们的上下文中接收上下文,function() {}
函数语法使用绑定(bind)到它们的上下文,或者通过它们在其中定义的上下文隐式地使用,或者显式使用此绑定(bind) 方法。
因此,使用类的替代方法是将一个简单的对象绑定(bind)到该方法,例如:
const call_method = require('../hereIam.mjs');
const process_db = async function() {
console.log(this);
call_method(this);
};
console.log(this);
const context = {
name: 'bound context',
parent_method: async function() {
console.log('Good evening');
}
}
process_db.bind(context)();
假设 hereIam.mjs
包含:
module.exports = parent_this => console.log(parent_this);
然后脚本会输出:
{}
{ name: 'bound context',
parent_method: [AsyncFunction: parent_method] }
{ name: 'bound context',
parent_method: [AsyncFunction: parent_method] }
关于javascript - expressjs server.js 这是未定义的,我如何引用服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52839529/