0

edit: I found the problem with my code - see my answer for the solution.

Just a quick question:

I want to access an instance of an class inside of another class - how can i do that? Here is a quick example of my problem:

var instanceA = new ClassA();

function ClassA(){
    var instanceB = null;

    this.start = function(){
        instanceB = new ClassB();
        instanceB.start();
    }

    this.action = function(){
        console.log('works not');
    }
} 

function ClassB(){
    this.start = function(){
        instanceA.action(); // this throws: Uncaught ReferenceError: instacneA is not defined 
    }
} 
jacksbox
  • 911
  • 1
  • 11
  • 24

3 Answers3

1

Pass it to the function:

this.start = function(instA) { ... }
instanceB.start(instanceA);

Or, if this instance is going to be reused in more than one method, pass it to constructor

function ClassB(instA) {
    this.instanceA = instA;
    this.start = function() { this.instanceA.action(); }
}

P.S. global variables are evil (most of the time). var instanceA = ... creates one. So, if it's just a quick prototype - it's ok. If not - try to avoid this

J0HN
  • 26,063
  • 5
  • 54
  • 85
0

Although your example seems to work fine when you call instanceA.start() - http://jsfiddle.net/infernalbadger/U5aUd/

It would probably be better to pass the instance of ClassA (this) to ClassB instead of relying on the global:

function ClassA(){
    var instanceB = null;
    var self = this;             // Save instance of ClassA
    this.start = function(){
        instanceB = new ClassB();
        instanceB.start(self);   // Pass to ClassB
    }

    this.action = function(){
        console.log('works not');
    }
} 

function ClassB(){
    this.start = function(a){       // Use passed in instance of ClassA
        a.action(); 
    }
} 

http://jsfiddle.net/infernalbadger/U5aUd/1/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
0

ok, i´m sorry - i found the problem:

I was using jquery and have created the instanceA variable inside the $(document).ready function.

When i create instanceA before the $(document).ready function it works.

So, even if i solved my problem i don´t understand it. can someone explain to me why my first approach didn´t work?

jacksbox
  • 911
  • 1
  • 11
  • 24