我有这个代码,它是我的用户类的一部分。当我调用此函数时:
user = new User();
user.regUser("john", "john@doe.com", "john123", function() { });
我收到错误
Uncaught TypeError: Object #<Database> has no method 'writeDb'
用户类中的功能:
User.prototype.regUser = function(name, email, password, cb) {
this.db.exec("SELECT * from users WHERE user_email='"+email+"';", function(results) {
var len = results.rows.length;
if (typeof(cb) == 'function') {
if (len < 1) {
this.name = name;
this.email = email;
this.password = password;
this.writeDb();
cb(true); // username doesn't exists
} else {
cb(false); // username already exists
}
}
});
}
问题可能是在我的函数的嵌套函数中调用'this'变量吗?因为在其他功能不工作时是嵌套的。我该如何解决这个问题?
答案 0 :(得分:2)
您假设“this”对象是回调中的User类。只需声明一个闭包变量来捕获“this”对象。试试这个;
User.prototype.regUser = function(name, email, password, cb) {
var user = this;
user.db.exec("SELECT * from users WHERE user_email='"+email+"';", function(results) {
var len = results.rows.length;
if (typeof(cb) == 'function') {
if (len < 1) {
user.name = name;
user.email = email;
user.password = password;
user.db.writeDb();
cb(true); // username doesn't exists
} else {
cb(false); // username already exists
}
}
});
}