I內有以下代碼沒有訪問該:從嵌套回調
var Company = function(app) {
this.crypto = require('ezcrypto').Crypto;
var Company = require('../models/company.js');
this.company = new Company(app);
}
// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(this.company); // Undefined
this.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}
// Get company with just their email address
Company.prototype.hashPassword = function (password, callback) {
if(typeof password !== 'string') {
var err = 'Not a string.'
} else {
var result = {
password: this.crypto.SHA256(password)
};
}
if (err) {
return callback(err);
}
return callback(null, result);
}
module.exports = Company;
的問題是,this.company
被該代碼塊的線11未定義的。
我知道this
是不是我認爲,但我不知道如何重構獲得訪問正確的this
。
您的hashPassword函數不是異步-.- – Raynos 2012-01-07 16:02:49
@Raynos我做錯了什麼? – 2012-01-07 16:30:15
您應該返回結果或錯誤。沒有必要使用回調,你允許從方法 – Raynos 2012-01-07 16:38:42