0

我遇到了以下问题。

我有不同的对象,例如:

使用方法的用户:id、用户名、名字、姓氏
文章:使用其他方法;

我想添加动态方法,如 getById、getByUsername 等。

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');

当函数中没有参数时,像这样的动态添加方法可以正常工作。所有方法都定义得很好,但是当我将它们称为更改(当然)时,我只有最后一个函数。

如果有人可以帮助我,我整天都在这上面,我仍然找不到解决方案。

4

2 回答 2

0

I solve my problem, when I was calling the function ByX the value of key was the last one in my object. So I put the function in a closure. But inside the closure this didn't refer to find but a general object.

So I just pass this inside my closure.

for(var key in Object){
    var query = 'SELECT * FROM user WHERE ' + key + "=\'";

        (function(insideQuery, obj){
            console.log(obj);
            addMethod("By"+key, obj, function(args) {

                    insideQuery+= args + "\'";
                    console.log(insideQuery);
                    return(connection.query(insideQuery));
                });

        })(query, this);
    }


function addMethod(key, obj,  fn){
  obj[key] = fn;
}

And it's doing exactly what I want.

于 2013-10-29T15:55:57.607 回答
0
var User = function(id, username, firstname, lastname) {
               this.name = 'user';
               this.id = id; 
               this.username = username;
               this.firstname = firstname; 
               this. lastname = lastname;
           };



var Find = function(objectName){

               var object = new objectName();

               // I have a first method all 
               // this refers to find object
               this.all = connection.query("SELECT * FROM " + objectName);


               //then I want to add ByX method, X taking the values id, username ...

               for( key in object ) {
                   if(key != "name") { // I exclude name method of user

                       var query = "SELECT * FROM user WHERE " + key + "=" ; 

                       this['By'+key] =  function(args) {
                           query += args;
                           return(connection.query(query);
                      };

               }



// then In my code

var find = new Find('User');
var list = find.ByX(something);
    list
        .on("error", function(err){
            console.log(err);
        })
        .on('result' function(row){
            console.log(row);
        })
   ;

当代码被编译时,对象 Find 有方法 ByX,但是当我运行 find.ByX(something);

传递给最后一个值的键恰好是姓氏。它运行了

var query = "SELECT * FROM user WHERE " + key + "=" ;
function(args) { 
        query += args; // query is recalculated and key is now lastname;
        ...
}

我在代码的其他地方以这种方式做到了,但似乎是因为函数正在等待 args 值,因此未设置查询。

于 2013-10-27T09:40:04.130 回答