gpt4 book ai didi

javascript - 如何监听 Javascript 中的变量变化?

转载 作者:IT老高 更新时间:2023-10-28 23:16:51 26 4
gpt4 key购买 nike

我一直在使用 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”现在在回调函数的范围内,而不是类。有没有人有任何想法来完成我想要的?我不希望有一个处理程序对象必须对对象进行数据库调用,但现在我真的被它异步的问题难住了。

最佳答案

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

关于javascript - 如何监听 Javascript 中的变量变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3637763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com