我正在使用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
我该如何解决? 为什么会这样?
答案 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);
}