如何在Javascript中监听variables?

我一直在使用Node.js和CouchDB。 我想要做的是在一个对象内进行数据库调用。 这是我现在正在看的场景:

var foo = new function(){ this.bar = null; var bar; calltoDb( ... , function(){ // what i want to do: // this.bar = dbResponse.bar; bar = dbResponse.bar; }); this.bar = bar; } 

所有这一切的问题是,CouchDBcallback是asynchronous的,“this.bar”现在在callback函数的范围内,而不是类。 有没有人有任何想法来完成我想要的? 我宁愿不要有一个处理程序对象,必须进行数据库调用的对象,但现在我真的很难与asynchronous的问题。

       

网上收集的解决方案 "如何在Javascript中监听variables?"

只要保持this的参考:

 function Foo() { var that = this; // get a reference to the current 'this' this.bar = null; calltoDb( ... , function(){ that.bar = dbResponse.bar; // closure ftw, 'that' still points to the old 'this' // even though the function gets called in a different context than 'Foo' // 'that' is still in the scope and can therefore be used }); }; // this is the correct way to use the new keyword var myFoo = new Foo(); // create a new instance of 'Foo' and bind it to 'myFoo' 

保存this的引用,如下所示:

 var foo = this; calltoDb( ... , function(){ // what i want to do: // this.bar = dbResponse.bar; foo.bar = dbResponse.bar; });