During instantiating an object VarA of ClassA I pass in a variable VarB which acts as a placeholder for an object of ClassB. After VarA is instantiated; somewhere later in the pipeline I assign newly instantiated object of ClassB TO VarB.
In ClassA I save reference to VarB & then use this to do any work.
The problem I am facing is that when I try to use any method on VarA that depends upon VarB, I get errors saying VarB is undefined. This confuses me because before I use these methods I make sure that VarB is properly instantiated. And since I am saving the reference to VarB, it should be pointing to the corect object, right?
UPDATE – Code sample as requested.
var varA, varB;
// Code
varA = new ClassA({
varB: varB
});
// Code
varB = new ClassB({
attributeB: "SOME_VALUE",
});
// Class Definition for ClassA which uses varB
var ClassA = Class.extend({
varB: {},
init: function(settings) {
this.varB = settings.varB;
},
dummyMethod: function() {
// Do Something with varB.attributeB
}
});
Not sure if this matters but I am using John Resig’s Class Extend Util for Simple JavaScript Inheritance. as the base class of all my Classes.
If you’ve got something like this:
and then later, when you’re ready, you do this:
then what that “VarA” object is holding onto is the “null” value you passed in, and you’ve changed the value of “VarB” to something else. There’s no way to do what you describe, at least not exactly. JavaScript is strictly pass by value, which means that when you make a function call, you’re passing the value of the argument expression to the function. Inside the “ClassA” constructor, the fact that the “null” happened to come from a variable in the calling scope called “VarB” is completely hidden; it’s just a “null”.
Now, what you can do is this:
and then later:
In that case, you would not be changing the value of “VarB”; you’d be changing the value of a property of the object referenced by “VarB”. If the “ClassA” code were written to stash that parameter and refer to its “actualB” property, then it would work.