I have a problem with my javascript code. I have this prototype and I want to have it in a way where you can add ‘middleware’ or how you’d call it. (like in ExpressJS, app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(...))
var Server = function(...){
...
};
Server.prototype.log = function(data){
console.log(data);
};
console.log(typeof(Server.prototype.log)); //function
So I changed it to a way where I add the functions by calling a function, so i can later implement something like _add('fnName', loadUser, function(...)).
var Server = function(...){
...
};
_add = function(fnName, fn){
Server.prototype.fnName = fn;
console.log(typeof(Server.prototype.fnName)); //always function
};
_add('log', function(data){
console.log(data);
});
console.log(typeof(Server.prototype.log)); //undefined
However this doesn’t work. The prototype isn’t changed.
I don’t want to do it like in ExpressJS (you add to an instance, not the prototype) because a Server object will be created for every user (in combination with socket.io), so adding functions to objects will be more overhead than adding to the prototype whose functions are available in all instances.
You need to use
Server.prototype[fnName]instead, becauseServer.prototype.fnNamedefines a function calledfnNameon the Server’s prototype.So in your example:
Code:
See this snippet.