好的,这就是我所拥有的:
const http = require("http");
const Server = function(){
this.context = {};
};
Server.prototype.callback = function(req, res){
console.log(this.context);
};
Server.prototype.listen = function(...arguments){
const server = http.createServer(this.callback);
return server.listen(...arguments);
};
module.exports = Server;
它记录context
如undefined
,但是当我调用没有 http.createServer
的函数时它有效,为什么以及如何修复它?
最佳答案
您需要将对象附加到回调。当您将 this.callback
作为参数传递时,它仅传递回调,并且没有对象的附件。因此,当 http.createServer()
调用您的回调时,它会以常规函数的形式调用 callback()
方法以及 this
的对象值丢失了。
您可以通过更改此来修复:
http.createServer(this.callback);
对此:
http.createServer(this.callback.bind(this));
将方法作为回调传递时,这是一个非常常见的问题。另一种选择是这样的:
http.createServer(() => this.callback());
关于javascript - Nodejs http.createServer 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60908896/