gpt4 book ai didi

node.js - 如何 "subclass"Node.js 模块

转载 作者:太空宇宙 更新时间:2023-11-03 22:00:39 26 4
gpt4 key购买 nike

多年来我主要是一名 Perl 编码员,但也有 C++ 背景,所以我来自“经典”OO 背景,现在正在学习 Node.js。我刚刚读完The Principles of Object-Oriented JavaScript ,它很好地向像我这样具有古典思想的人解释了 OO 的 JS 概念。但我留下了一个问题,特别是与 Node.js 和继承相关的问题。如果我仍然使用“经典”词汇来解释我的问题,请原谅。

假设我有一个模块lib/foo.js:

function foo() {
console.log('Foo was called');
}

module.exports.foo = foo;

我想在另一个模块 lib/bar.js 中对其进行“子类化”:

var foo = require('foo.js');

// Do some magic here with *.prototype, maybe?

function bar() {
console.log('Bar was called');
}

module.exports.bar = bar;

这样我的主脚本就可以做到这一点:

var bar = require('lib/bar.js');

bar.foo(); // Output "Foo was called"
bar.bar(); // Output "Bar was called"

这可能吗?如果是这样,我错过了什么?

或者这是一种反模式?或者根本不可能?我该怎么办?

最佳答案

这是我的做法,重写 request module 中的一个方法。 警告:许多 Node 模块对于扩展(包括请求)的设计很差,因为它们在构造函数中做了太多的事情。不仅仅是大量的参数选项,还包括启动 IO、连接等。例如,request 将 http 连接(最终)作为构造函数的一部分。没有显式的 .call().goDoIt() 方法。

在我的示例中,我想使用查询字符串而不是 qs 来格式化表单。我的模块被巧妙地命名为“MyRequest”。在名为 myrequest.js 的单独文件中,您有:

var Request = require('request/request.js');
var querystring = require('querystring');

MyRequest.prototype = Object.create(Request.prototype);
MyRequest.prototype.constructor = MyRequest;

// jury rig the constructor to do "just enough". Don't parse all the gazillion options
// In my case, all I wanted to patch was for a POST request
function MyRequest(options, callbackfn) {
"use strict";
if (callbackfn)
options.callback = callbackfn;
options.method = options.method || 'POST'; // used currently only for posts
Request.prototype.constructor.call(this, options);
// ^^^ this will trigger everything, including the actual http request (icky)
// so at this point you can't change anything more
}

// override form method to use querystring to do the stringify
MyRequest.prototype.form = function (form) {
"use strict";
if (form) {
this.setHeader('content-type', 'application/x-www-form-urlencoded; charset=utf-8');
this.body = querystring.stringify(form).toString('utf8');
// note that this.body and this.setHeader are fields/methods inherited from Request, not added in MyRequest.
return this;
}

else
return Request.prototype.form.apply(this, arguments);
};

然后,在您的应用程序中,而不是

var Request = require("request");
Request(url, function(err, resp, body)
{
// do something here
});

你走

var MyRequest = require("lib/myrequest");
MyRequest(url, function(err, resp, body)
{
// do that same something here
});

我不是 JavaScript 专家,所以可能有更好的方法......

关于node.js - 如何 "subclass"Node.js 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26309012/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com