Javascript 在嵌套回调中没有对此的访问权限
我有以下代码:Javascript 在嵌套回调中没有对此的访问权限,javascript,node.js,Javascript,Node.js,我有以下代码: 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, e
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行没有定义
我知道
这个
不是我想的那样,但我不确定如何重构以访问正确的这个
所以有两个解决方案
首先是脏的
Company.prototype.create = function (name, contact, email, password, callback) {
var that = this; // just capture this in the clojure <-
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(that.company); // Undefined
that.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}
您可以通过在
公司中声明另一个变量来引用此
。创建
范围,如下所示:
// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
var me = this;
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(me.company); // Undefined - not anymore
me.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}
未经测试,但它应该是这样工作的。只是主观偏好,请使用您最喜欢的。@megakorre它们都很脏:(@Raynos你会怎么做?@JoshSmith我会为内部函数的
this
值默认为外部函数的this
值以及使用两个脏解决方案而愤怒。或者,你可以在实例上使用.bindAll
模式。(请参阅下划线.bindAll)您的hashPassword函数不是异步的-。-@Raynos我做错了什么?您应该返回结果或错误。不需要使用回调,您可以从中返回值methods@Raynos真的吗?我想我必须使用回调来实现非阻塞?或者我只是个弱智?你的简单弱智,回调不会让我t非阻塞。执行异步IO使其成为非阻塞。请查看hashpassword
执行阻塞操作,然后以阻塞方式调用回调
// Create the company
Company.prototype.create = function (name, contact, email, password, callback) {
var me = this;
this.hashPassword(password, function(err, result) {
if (err) throw err;
console.log(me.company); // Undefined - not anymore
me.company.create(name, contact, email, result.password, function(err, result) {
if (err) {
return callback(err);
}
return callback(null, result);
});
});
}