Javascript对象继承和异步

Javascript对象继承和异步,javascript,inheritance,asynchronous,firebase,Javascript,Inheritance,Asynchronous,Firebase,当我在Javascript中有这样一个对象时: var Foo = { bar: function(location, callback){ var ref = new Firebase(location); alert(location); // outputs correct, different value when called twice with different locations ref.on('value', function(

当我在Javascript中有这样一个对象时:

var Foo = {

   bar: function(location, callback){

     var ref = new Firebase(location);   
     alert(location); // outputs correct, different value when called twice with different locations

     ref.on('value', function(remote) {
         callback(remote, location);
         alert(location); // outputs last value that was given to Foo.bar, set synchronously, 
                          // but when asynchronously getting the value, only last given to Foo.bar() is retrieved
     }.bind(this)) // bind to .bar scope

   }
}
然后做:

Foo.bar("some/location", function(remote, location){
   alert(remote) // "some/location"
});
这将返回一些
远程
对象和原始的请求的
位置
(我在本地使用这些引用,因此无论调用以何种顺序返回,我都可以将它们放在本地客户端的正确位置)

现在,当我尝试多个
Foo.bar
时,如下所示:

Foo.bar("some/location", function(remote, location){
   alert(location) // after callback has responded:  "other/location"
});
// some ms have passed, no response/callback from server yet...
Foo.bar("other/location", function(remote, location){
   alert(location) // after callback has responded:  "other/location"
});
location
变量似乎覆盖了第一个
Foo.bar()
,这很奇怪,因为据我所知,该变量在
Foo
的私有范围内,不应该被触摸

即使我这样做:

 var Fuu = Object.create(Foo);
据我所知,它至少会创建一个全新的
对象
,只继承最后设置的变量,但从一开始就应该在它自己的范围内。还是我误解了一些基本的东西?还是我正在使用的异步
Firebase

当我执行以下操作时,继承是否不同?如何/为什么

var Foo = function(){

    this.bar = function(){

    }

}
澄清:在任一异步调用
回调
后,给Foo.bar()的最后一个
位置
变量似乎覆盖了Firebase范围内的第一个变量,我得到了正确的
远程
对象,但没有得到正确的关联
位置
,这反映了
远程
对象在我的客户机代码中的本地位置

Update*在我的问题中,我将
Async()
更改为
Firebase()
,实际上我正在使用它,但我不认为这是它的错,因为我只是传递一个变量,并将它绑定到
this
以保持te引用,但它看起来像是,因为
Foo.bar
是同一个函数(对象?),它将第一个给定的
位置
变量覆盖到最后一个收到的
Foo.bar
变量


更新添加了
。将(this)
绑定到问题,将变量传递给异步函数,并使错误输出的回调函数

可能会回答我的问题:

这实际上是调用函数时进行的绑定,
而它所引用的内容完全由调用位置决定
调用该函数

这似乎也解释了我对
这个
绑定的误解:

function foo() {
    console.log( this.a );
}

var obj = {
    a: 2,
    foo: foo
};

var bar = obj.foo; // function reference/alias!

var a = "oops, global"; // `a` also property on global object

bar(); // "oops, global"

有人能确认我的
.bind(this)
可能是对这种意外行为的解释,并且这篇文章是正确的吗?

你的
Foo
似乎很好,可能是
Async
@Bergi有问题……什么是
Async
?我在Firebase文档中找不到它Firebase文档中没有任何东西。你能分享一下你在用异步代码做什么吗?我想你只是从根位置创建了一个Firebase引用。ref.toString不应该有这个位置吗?这篇文章是正确的(就我略读它所知),但是你尝试
.bind()
ing是徒劳的。您没有在代码中使用
,因此没有任何问题。您可能需要再次阅读:明确地说,
无论如何都不引用函数的词法范围。“除非该作用域是全局作用域”,这篇文章似乎忘记了添加(这只是造成更多混乱的原因),而
。bind(this)
可能不会像我认为的那样做,它不是徒劳的,因为没有它,
location
变量在Firebase ref回调函数中就不可读。不<代码>位置
在范围内可用。您不需要做任何明确的事情来提供它。至少绑定未以任何方式引用的。