tags:

views:

688

answers:

4

How do I define nested class in Java Script.

Here is the code snippet I have:

objA = new TestA();

function TestB ()
{
   this.testPrint = function ()
  {
     print ( " Inside testPrint " );
  }
}

function TestA ()
{
   var myObjB = new TestB();
}

Now I am trying to access testPrint using objA

objA.myObjB.testPrint();

But its giving error "objA has no properties"

How can I access testB method using objA handler?

+5  A: 

use this.myObjB instead of var myObjB

Leo
+3  A: 

Object literals:

var objA = {
    myObjB: {
       testPrint: function(){
          print("Inside test print");
       }
    }
};

objA.myObjB.testPrint();
Aaron Maenpaa
Who voted this down? This is a perfectly valid answer, missing only "objA.myObjB.testPrint()"!
The Wicked Flea
+1  A: 

If you're trying to do inheritance then you may want to consider the prototype keyword.

var myObjB = function(){
    this.testPrint = function () {
       print ( " Inside testPrint " );
    }
}

var myObjA = new myObjB();
myObjA.prototype = {
   var1 : "hello world",
   test : function(){
      this.testPrint(this.var1);
   }
}

(i hope that made sense)

Sugendran
+1  A: 

Your definition of TestA does not expose any public members. To expose myObjB, you need to make it public:

function TestA() {
    this.myObjB = new TestB();
}
var objA = new TestA();
harley.333