When I have an Object like this in 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
}
}
And then do:
Foo.bar("some/location", function(remote, location){
alert(remote) // "some/location"
});
This would get back some remote
object, and the original, requested location
(which reference I use locally, so when, in whatever order the calls come back, I can put them in the right place in the local client)
Now, when I try multiple Foo.bar
like this:
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"
});
The location
variable seems to override the first Foo.bar()
, which is strange, because as far as I know that variable is in the private scope of Foo
and should not be touched?
Not even when I do:
var Fuu = Object.create(Foo);
Which, as far as I know, would at least create a completely new Object
, only inheriting the last set variables, but from its inception on out, should be in its own scope. Or am I misunderstanding some fundamental thing here? Or is it the asynchronous Firebase
library I'm using?
Is the inheritance different when I would do the following? And how/why?
var Foo = function(){
this.bar = function(){
}
}
To clarify: After either async calls callback
, the last location
variable given to Foo.bar() seems to overwrite the first within the Firebase scope, and I get the right remote
object, but not the right, associated location
, which reflects where the remote
object should go in my client code, locally.
Update* I changed Async()
to Firebase()
in my question, which I'm actually using, but I don't think it is its fault, because I'm just passing along a variable, and binding it to this
to keep te reference, but it looks like, because Foo.bar
is the same function(object?), it overwrites the first given location
variable to the last one that Foo.bar
received..
Update Added .bind(this)
to the question, to pass the variable to the async function and made the callback function that output wrongly