所以我需要一些帮助我现在已经坚持了几个小时..
问题是我正在创建名为Rank的对象。 Rank需要在mongodb中进行一些DB调用以获取数据以填充矩阵,然后需要在此矩阵上执行更多嵌套函数调用,这是我尚未编写的。问题在于,当我调用doRank()时,它会获得公司和交易,并且似乎将它们放入Rank中,但是当我调用createMatrix时,它无法访问这个'
我尝试在doRank()中的每个函数上使用.bind(this)来防止该方法不存在的错误,但是当我在doRank()结束时执行console.log时矩阵的结果是不确定的。
function Rank(dampingfactor){
this.damping_factor = dampingfactor;
this.companies = null;
this.transactions = null;
this.matrix = null;
this.doRank(function(){
//companies returns valid
console.log(this.companies);
//transactions return valid
console.log(this.transactions);
//matrix returns as undefined... help here please
console.log(this.matrix);
});
};
Rank.prototype.doRank = function(callback) {
this.getTransactions(function() {
this.getCompanies(function () {
this.createMatrix(function(){
callback();
}.bind(this));
}.bind(this));
}.bind(this));
};
Rank.prototype.getTransactions = function(callback){
Transaction.find({}, function(err, transactions) {
//blah blah blah
this.transaction = transactions;
callback();
});
};
Rank.prototype.getCompanies = function(callback){
Company.find({}, function(err, comps) {
//blah blah blah
this.transaction = comps;
callback();
});
};
Rank.prototype.createMatrix = function(callback){
console.log(this.companies)
//this returns "null"
var matrix = new Array(_.size(this.companies));
for(var i = 0; i < _.size(this.companies); i++){
matrix[i] = new Array(_.size(this.companies));
for(var j=0; j < _.size(this.companies); j++){
matrix[i][j] = 0;
}
}
this.matrix = matrix;
callback();
};
答案 0 :(得分:3)
您在getTransactions
和getCompanies
内的AJAX回调函数中丢失了上下文。试试这个:
Rank.prototype.getTransactions = function(callback) {
Transaction.find({}, function(err, transactions) {
//blah blah blah
this.transaction = transactions;
callback();
}.bind(this));
};
Rank.prototype.getCompanies = function(callback) {
Company.find({}, function(err, comps) {
//blah blah blah
this.transaction = comps;
callback();
}.bind(this));
};
答案 1 :(得分:2)
this
在嵌套函数调用中使用时不再引用对象,因为该函数没有父对象。如果您将this
分配给变量,例如var self = this
,您可以在嵌套函数调用中正常访问它。