因为数据库本身就是一个单独的对象,所以调用它会丢失this
var neo4j = require('neo4j');
var db = new neo4j.GraphDatabase('http://localhost:7474');
function MyObject(id){this.id = id}
MyObject.prototype.myQuery = function(){
db.query('Some Query',{args:params},function(callback){
//this in here is some neo4j db related object.
//instead of MyObject
console.log(this.id); //undefined
});
}
myObject = new MyObject(9);
myObject.myQuery(); //undefined
进行数据库调用但仍有this
的任何解决方法是从db的回调中引用原始目标对象吗?
答案 0 :(得分:3)
在通话前缓存它:
MyObject.prototype.myQuery = function(){
var self = this;
db.query('QUERY',{args:params},function(callback){
//If you use self here, it will work.
console.log(self.id);
});
}
答案 1 :(得分:2)
除了将其保存到变量之外,您还可以将this
绑定到一个函数,如下所示:
MyObject.prototype.myQuery = function(){
db.query('Some Query',{args:params},function(callback){
//this in here is some neo4j db related object.
//instead of MyObject
console.log(this.id); //undefined
}.bind(this));
}
...或使用ES6中的箭头功能,即使它还不是一个选项...
答案 2 :(得分:0)
您可以在调用this
方法之前保存db.query
,如下所示:
MyObject.prototype.myQuery = function(){
var thisQuery = this;
db.query('QUERY',{args:params},function(callback){
// Now you can use thisQuery to refer to your query object
}
}