I got the following problem.
I have different object like:
user with the method : id, username, firstname, lastname
article :with some other method;
i want to add dynamic method like getById, getByUsername etc.
var object = new Object() ; // Object can take the value user, article or other. </code>
for(var key in object) {
this["getBy" + key]= function(args) {
var result = query("SELECT * FROM " + object.name + ' WHERE ' key + "=" +args);
console.log(key); //always return the last key of object
return(result);
}
// then
var user = new User();
user.getByUsername('someone');
The dynamic add of method like this works fine when there is no argument in the function. All the method are well define but when I call them key as change (of course) to I just have the last function.
If someone can help me, I spend all my day on this, and I still can't find a solution.
user
object ? – Newben 16 hours agothis
refers to ?user
object, but intuively, what seems to happen is that each key in your loop must override its precedent – Newben 16 hours agothis
in your code currently refer to the global (or in node, the module global) object. Or it may even refer to null in the case of ES5 strict mode. Sincethis
in javascript depends on how the surrounding code gets executed you need to provide the code for that as well - is it a constructor? A callback? An event handler? – slebetman 16 hours agoSELECT
is difficult and not maintainable, usually there are standard methods on anUser
,Article
as entities of a database, you build more difficultSELECT
by building a query and not building a method. – GeoPhoenix 10 hours ago