javascript - Nodejs http.createServer 回调

标签 javascript node.js

好的,这就是我所拥有的:

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;

它记录contextundefined ,但是当我调用没有 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/

相关文章:

javascript - 应用程序脚本从 Date() 转换为可读的内容

javascript - 在页面加载 AngularJS 时启动 Bootstrap 模式

javascript - node-webkit 如何在另一个窗口中调用一个函数?

javascript - 允许 Joi 中的可选参数而不指定它们

javascript - 如何覆盖 javascript 中返回的嵌套方法?

javascript - 将 Accordion 选项卡滑动到浏览器顶部

node.js - 如何在 Node JS 的本地变量中存储 GET 请求的响应

arrays - 在数组中搜索数据 [Node.JS]

node.js - 如何远程启动和停止 meteor 服务器?

javascript - AngularJS 指令中的可选表达式属性