NodeJs undefined不是一个函数

时间:2015-10-01 06:53:42

标签: javascript node.js

我正在使用NodeJ来运行此代码 这是我的自定义模块

call = {};
call.hangup = {
    searching: function(number, mysql, validator){
        this.number = number;
        this.mysql = mysql;
        this.validator = validator;
        var query = "{sql...}";
        try
        {   
            mysql.query(query, function(err, rows, fields) {        
            if (err) throw err; 
                if(!validator.isNull(rows))
                {                                       
                    return rows.leadid;                     
                }else {
                    return false;
                }
            });
        }catch(error)
        {
            console.log(error);
        }
    },
    test: function(number, mysql, validator){
        var self = this;
        this.number = number;
        this.mysql = mysql;
        this.validator = validator;
        var result = self.searching(number, mysql, validator);
        console.log(result);
    }
};
module.exports = call;

然后在我的主文件中调用测试函数

call.hangup.test(number, connection, validator);

但我在我的控制台中收到此错误代码:

                var result = self.searching(leadid, mysql, validator);
                                  ^
TypeError: undefined is not a function

我该如何解决? 为什么会这样?

1 个答案:

答案 0 :(得分:1)

您的this引用(您分配给self variable)指向test function且测试功能没有名为searching的功能。这就是您收到此错误的原因。您应该以这种方式searching

调用call.hangup.searching函数
call = {};
call.hangup = {
    searching: function(number, mysql, validator){
        this.number = number;
        this.mysql = mysql;
        this.validator = validator;
        var query = "{sql...}";
        try
        {   
            mysql.query(query, function(err, rows, fields) {        
            if (err) throw err; 
                if(!validator.isNull(rows))
                {                                       
                    return rows.leadid;                     
                }else {
                    return false;
                }
            });
        }catch(error)
        {
            console.log(error);
        }
    },

    test: function(number, mysql, validator){

        this.number = number;
        this.mysql = mysql;
        this.validator = validator;
        var result = call.hangup.searching(number, mysql, validator);
        console.log(result);
    }
};
module.exports = call;

修改 您还可以将self变量分配给call.hangup

test: function(number, mysql, validator){
            var self = call.hangup;
            this.number = number;
            this.mysql = mysql;
            this.validator = validator;
            var result = self.searching(number, mysql, validator);
            console.log(result);
        }