Coderer
Coderer

Reputation: 27294

How do I avoid "variable may not have been initialized" when referencing a JavaScript parent object?

I know there are a lot of "how do I avoid this warning" questions, but it looks like mine is the first specific to JavaScript. In this case, I want to reference the thing I'm initializing inside its own declaration, like so:

var foo = new Foo({
  bar: new Bar({
    x: function(){
      doStuff(foo);
    }
  });
});

(If this looks familiar, maybe you've used ExtJS before -- this is how most of their stuff is built.)

When I call foo.bar.x(), I want to point back to the Foo (foo) that owns the Bar (bar) that's calling the function (x). This works, but my Eclipse warns me that "foo may not have been initialized", referencing the call to doStuff(); -- because, when the engine first sees the line, we haven't finished defining foo yet. Of course, x() can't be called unless foo is constructed successfully, but my style checker apparently hasn't figured that out.

So I'm at a loss for how to deal with this. Should I ignore the warning? Is there a way to mark it as such, so I don't get a warning anymore? Am I doing this wrong? Should I pass my reference in a different manner?

Upvotes: 5

Views: 4189

Answers (4)

Raynos
Raynos

Reputation: 169451

var Foo = function() { }

var Bar = function (obj) {
  // foo is not initialized
  obj.x();
  // called doStuff with undefined
}

var foo = new Foo({
  bar: new Bar({
    x: function(){
      doStuff(foo);
    }
  });
});

Eclipse is right. Again if you want a better analysis system consider using WebStorm 3.0 or Visual Studio 11 as your JS IDE.

Upvotes: 2

nrabinowitz
nrabinowitz

Reputation: 55678

I think @RobG is right, that this is an Eclipse issue and it's probably best just to deal with it. But if you wanted to avoid it, you can declare foo before you initialize it, and I bet this will keep Eclipse from complaining:

var foo;
foo = new Foo({
  bar: new Bar({
    x: function(){
      doStuff(foo);
    }
  });
});

Upvotes: 0

RobG
RobG

Reputation: 147453

It's nothing to do with javascript, but probably something to do with Eclipse. The variable foo can be declared anywhere, since variable declarations are processed before any code is executed. It can also be initialised at any time before doStuff is called (though initialising variables without declaring them is considered bad form).

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116140

First, a Foo is constructed. To its constructor, a new Bar is passed, which is passed a function using a variable foo.

But foo is only assigned a value after the constructor of Foo is finished. At that point, the function is already declared, using the undeclared variable foo. If the function is used in the constructor of either Bar or Foo, it will fail.

Upvotes: 0

Related Questions