开发者

In JavaScript HOWTO pass uninstantiated object to constructor call of different class, which is instantiated later in the timeline?

开发者 https://www.devze.com 2023-03-15 15:40 出处:网络
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

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 开发者_如何学JAVAClasses.


If you've got something like this:

var VarB = null, VarA = new ClassA(VarB);

and then later, when you're ready, you do this:

VarB = new ClassB();

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:

var VarB = { actualB: null }, VarA = new ClassA(VarB);

and then later:

VarB.actualB = new ClassB();

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消