什么是最好的(性能,内存方面的)来实现一种干净的方法来创建一个类,或者某种方法来正确地构造代码,共享两个变量(req,res),这些变量具有一个很好的对象大小。
是的,对于那些使用Node.js的人来说,它是req和res变量,但是它是不相关的。
这就是我迄今为止尝试过的:
function Client(req, res){
var self = this;
self.req = req;
self.res = res;
route.call(self);
handleRoute.call(self);
handleRequestData.call(self);
}
function route(){
var self = this;
self.req.route = // ...
}
function handleAuth(){
var self = this;
self.req.auth = // ...
}
function handleRequestData(){
var self = this;
self.req.data = // ...
}我想知道它是否可以改进,因为我提到了req和res是相当不错的对象,具有方法和属性。既然.call(self)通过实例,它会是最有效的方法吗?
而且,我也不喜欢使用"var self =this“,因为它一直是无用的。
顺便说一句,我不想用咖啡记录。
解决方案1. (由于大量通过req和res而失败)
让我们假设我们需要文件1. client.js
var Client = {
route: function(req, res){},
auth: function(req, res, callback){ callback(req, res); },
getData: function(req, res, callback){ callback(req, res); } // async
}文件2. main.js
var client = require('./client.js');
client.route(req, res); // fine because this is syncronous.
// This is where the problem is, massive passing through req and res parameters.
client.auth(req, res, function(req, res){
client.getData(req, res, function(req, res){
// Do something...
});
});发布于 2012-08-21 20:34:20
我不知道为什么您总是将上下文(this)保存在局部变量(self)中。您最好一路使用this,除非您需要将它带到具有不同作用域的本地对象中。
此外,还可以将原型中的其他方法链接起来,以获得对其中上下文的访问:
function Client(req, res){
this.req = req;
this.res = res;
this.route();
this.handleRoute();
this.handleRequestData();
}
Client.prototype.route = function(){
this.req.route = // ...
}
Client.prototype.handleAuth = function(){
this.req.auth = // ...
}
Client.prototype.handleRequestData = function(){
this.req.data = // ...
}如果不需要“公共”方法,只需:
function Client(req, res){
this.req = req;
this.res = res;
route.call(this);
handleRoute.call(this);
handleRequestData.call(this);
}
function route(){
this.req.route = // ...
}
function handleAuth(){
this.req.auth = // ...
}
function handleRequestData(){
this.req.data = // ...
}发布于 2012-08-21 20:37:22
您打算重用route、handleAuth和handleRequestData函数吗?它们可以是客户端构造函数的“私有”:
function Client(req, res) {
function route() {
//...
}
function handleAuth() {
//...
}
function handleRequestData() {
//...
}
route();
handleRoute();
handleRequestData();
}请注意,我没有将req和res设置为this成员。我不知道这在你的案子中是否是强制性的。而且,这只是可以完成的工作的开始;正如对此答案的注释中所述,每次创建新的Client时,都会创建私有函数的新实例,从而浪费资源。
更复杂的方法可以使用自调用函数表达式定义Client:
var Client = (function() {
function route(req, res) {
//...
}
function handleAuth(req, res) {
//...
}
function handleRequestData(req, res) {
//...
}
// This is the constructor function:
return function(req, res) {
route(req, res);
handleRoute(req, res);
handleRequestData(req, res);
}
})();在这里,Client被定义为最外层括号内的函数表达式的乘积。函数表达式返回构造函数,它可以访问闭包函数route、handleRoute和handleRequestData。请注意,这些函数中的每一个都使用req和res参数定义。这样,它们的行为就像静态的私有函数,无论this引用了什么,您都可以对它们进行编码和使用。
About self = this:众所周知,JavaScript可能会非常混淆this关键字。Some information here。因此,有时将this分配给一个名为self或me的闭包变量是很方便的。但不应该盲目地做.毕竟是任何事情。
https://stackoverflow.com/questions/12062483
复制相似问题