【问题标题】:How to listen for a variable change in Javascript?如何监听 Javascript 中的变量变化?
【发布时间】:2011-04-07 22:56:39
【问题描述】:

我一直在使用 Node.js 和 CouchDB。我想要做的是在对象中进行 db 调用。这是我现在正在查看的场景:

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;

}

所有这一切的问题在于 CouchDB 回调是异步的,“this.bar”现在在回调函数的范围内,而不是类。有没有人有任何想法来完成我想要的?我不希望有一个处理程序对象必须对对象进行数据库调用,但现在我真的被它异步的问题难住了。

【问题讨论】:

  • 欢迎来到 Stack Overflow,为一个好问题 +1。

标签: javascript asynchronous couchdb node.js


【解决方案1】:

只需保留对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'

【讨论】:

  • 我相信 OP 正在使用 new function... 技术来创建单例,所以他的代码本来就很好。
  • 那不是单例,他只是在创建一个单独的对象。我对单例的理解是,如果你再次调用构造函数,你会得到完全相同的对象。
  • 是的,new function(){} 产生一个对象,但 function(){} 本身本质上是一个匿名单例。
  • 这就是我想要的。谢谢。我正在尝试制作一个函数,顺便说一句,而不是单例,我今天盯着代码太久了,有点搞混了。
【解决方案2】:

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

var foo = this;
calltoDb( ... , function(){

  // what i want to do: 
  // this.bar = dbResponse.bar;

  foo.bar = dbResponse.bar;      

});

【讨论】:

  • node.js v2(其实是新的V8)支持函数绑定,所以不需要额外的变量传递this左右:calltoDB( ... ,function(){this.bar=dbResponse.bar}.bind(this));
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 2013-01-05
  • 1970-01-01
  • 2017-05-16
  • 2021-01-07
相关资源
最近更新 更多