0

I've been learning OOP and playing around in JavaScript, and was wondering how to get something that looks like this to work...

function myApp(){

   this.nav = function(){

      function toggle(state = 'show'){
          //toggle nav code...
      }

   toggle(); 
   }


}

var app = new myApp();
app.nav();

How would go about accessing the toggle function from here like this...

app.nav().toggle('hide');
1
  • Your function would have to return {toggle : function() {...}} to be chainable Commented Nov 6, 2016 at 0:42

3 Answers 3

2

You need to return this.
here an example:

function myApp(){
    this.nav = function(){
    this.toggle = function(state = 'show'){
      console.log(state);      
    }   
    this.toggle();
    return this;
  }
}

const app = new myApp();
app.nav(); // show
app.nav().toggle('hide'); // show hide

Also you need to attach the function to the object (this.toggle).
hope this help.

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

1 Comment

thanks, I was playing around with this I came across this scenario, and was curious
1

you should return the object to make the methods chainable.
your definition could be like:

function myApp(){
   var self= this;

   self.toggle = function(state = 'show'){
      //toggle nav code...
      //return self? to make it chainable too
   }

   self.nav = function(){
     self.toggle(); 
     return self;
   }
}

var app = new myApp();
app.nav();

but this is not the best implementation for oop :/

Comments

0

I will prefer like this:

function myApp(){

   this.nav = function(){
      var core = {
          toggle: toggle
      }
      function toggle(state = 'show'){
          if(state === "show") 
          {
            console.log("showing state");
          } else {
            console.log(state);
          }        
      }
      return core;
    }
}

var app = new myApp();
app.nav().toggle();
app.nav().toggle('close');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.