我正在努力(和新的)在Javascript中实现一个好的类模式。我在我的类函数的主体中定义我的本地变量和函数,然后将公共接口作为对象返回。
但是,当我尝试在我的一个方法中返回操作的更新结果时,我无法返回正确的'this'级别 - 它返回我的回调的内部范围,而不是操作的更新结果在我的对象上。感谢任何帮助!
例如
var u=require('./models').User();
u.findUserById('1', function(err, user) {console.log(user)});
在我的db中返回db回调对象,在下面的函数中:
function User() {
var user_uuid, local_email, local_password;
function generateHash(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
}
function validPassword(password, password_compare) {
return bcrypt.compareSync(password, password_compare);
}
function findUserByEmail(email, callback) {
conn.query("SELECT * FROM users WHERE local_email=$1 LIMIT 1", [email], function (error, result) {
//var user = this.User;
if (!error) {
if (result.rowCount > 0) {
local_email = result.rows[0].email;
user_uuid = result.rows[0].user_uuid;
//load rest of user obj
}
}
callback(error, this);
});
}
function findUserById(id, callback) {
conn.query("SELECT * FROM users WHERE user_uuid='' || $1 LIMIT 1", [id], function (error, result) {
if (result.rowCount > 0) {
//update
user_uuid = result.rows[0].user_uuid;
local_email = result.rows[0].local_email;
local_password = result.rows[0].local_password;
callback(null, this);
} else {
callback(null, this);
}
});
}
function save(callback) {
conn.query("SELECT * FROM users WHERE user_uuid='' || $1", [user_uuid], function (error, result) {
if (result.rowCount > 0) {
//update
conn.query("UPDATE users SET local_email=$1, local_password=$2 WHERE user_uuid=$3", [local_email, local_password, user_uuid], function (error, result) {
callback(error);
})
} else {
//insert
conn.query("INSERT users (user_uuid, local_email, local_password) VALUES ($1, $2, $3)", [require('node-uuid').v1(), local_email, local_password], function (error, result) {
callback(error);
})
}
})
}
return {
user_uuid: user_uuid,
local: {
email: local_email,
password: local_password
},
facebook: {
id: null,
token: null,
email: null,
name: null
},
twitter: {
id: null,
token: null,
displayName: null,
username: null
},
google: {
id: null,
token: null,
email: null,
name: null
},
generateHash: generateHash,
validPassword: validPassword,
findUserByEmail: findUserByEmail,
findUserById: findUserById,
save: save
}
};
答案 0 :(得分:0)
您必须指定"这个"的值到外部作用域中的变量和在内部作用域中使用该变量。