2

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());
2
  • 1
    You can definitely create nested functions, but the problems you are having probably relate to use of the this keyword. Have you read up on how this works in JavaScript? It's a bit different to what happens in class-based OO languages like Java. Commented Oct 28, 2011 at 5:35
  • There is a missing }; to close this.action1. Commented Oct 28, 2011 at 5:38

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.