【问题标题】:How to make database call without losing this?如何在不丢失这个的情况下进行数据库调用?
【发布时间】:2014-02-28 15:06:11
【问题描述】:

因为数据库本身就是一个单独的对象,所以调用它我输了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 引用数据库回调内部的原始预期对象?

【问题讨论】:

    标签: javascript node.js neo4j


    【解决方案1】:

    在调用之前缓存它:

    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);
        });
    }
    

    【讨论】:

    • 可以否决投票者解释什么是错的?对每个人都有用。
    • 用于保存此文件的其他常用名称是 _thisthat
    【解决方案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 中的箭头函数,即使它还不是一个选项...

    【讨论】:

      【解决方案3】:

      您可以在调用db.query 方法之前保存this,如下所示:

      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
        }
      }
      

      【讨论】:

        猜你喜欢
        • 2020-02-21
        • 1970-01-01
        • 2012-03-06
        • 2016-07-14
        • 2017-04-07
        • 1970-01-01
        • 2010-10-18
        • 2018-03-04
        • 2016-08-21
        相关资源
        最近更新 更多