Christopher
Christopher

Reputation: 13157

jS OOP nested functions

Ok this may be a noobolicious question as im new to OOP.

Im attempting to build something of a JS Object Library and was wondering if I could do it using nested functions??

var object = new function() {

    this.action1 = function () {
        this.dostuff1 = function () {
             return "dostuff1";
        };

     this.dostuff2 = function () {
          return "dostuff2";
     };                   
};

I am having trouble accessing the third level functions. Can I nest like this?

this.action2 = function () {
    return "action2";
}; 

alert(object.action1.dostuff2());

Upvotes: 2

Views: 2051

Answers (2)

Juri
Juri

Reputation: 32910

While Eberlin's answer is perfectly correct I'd suggest you to create a nested object which in turn again exposes functions rather than nesting functions itself. Otherwise this might become a maintainability nightmare.

Basically you could create

var Child = function(){
   //constructor
};

Child.prototype.doStuff2 = function(){
  return "dostuff2";
};

var Root = function(obj){
   //constructor
   this.child = obj;
};

Root.prototype.action1 = function(){
   return "doStuff1";
};

//usage
var myRoot = new Root(new Child());
myRoot.action1();
myRoot.child.action2();

Here's a live example: http://jsbin.com/ijotup/edit#javascript,live

Upvotes: 3

Adam Eberlin
Adam Eberlin

Reputation: 14205

See below for some code cleanup:

var o = (new function () {          // changed 'object' to 'o'
  this.action1 = (function () {     // added parentheses, not required.
    this.dostuff1 = (function () {  // does not return anything.
      return "dostuff1";            // and is also not the proper way to organize
    });                             // ** look at the javascript prototype
    return this;                    // now it does
  });                               // missing closing bracket

  this.dostuff2 = (function () {
    return "dostuff2";
  });                   
});

alert(o.action1().dostuff2());      // action1 is a function, not a variable.

Hope this helps. Also, here's a brief tutorial on the javascript prototype.

Upvotes: 2

Related Questions