[英]expressjs server.js this is undefined, how can I refer to server
在 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() {}
函数语法使用由它们定义的上下文隐式绑定到它们的上下文或使用此绑定方法显式绑定的上下文。
因此,使用类的替代方法是将一个简单的对象绑定到该方法,例如:
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] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.