在回调中使用JavaScript Node.js类方法并保留两个上下文,可以通过以下步骤实现:
const http = require('http');
const MyClass = require('./myClass');
const myObject = new MyClass();
const callback = () => {
myObject.myMethod();
};
或者使用bind方法:
const callback = function() {
myObject.myMethod();
}.bind(this);
http.createServer((req, res) => {
// 处理请求
callback();
}).listen(3000);
以上代码示例中,回调函数中调用了myObject的myMethod方法,并且保留了两个上下文。你可以根据实际需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云