Reputation: 90
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');
Upvotes: 0
Views: 59
Reputation: 1725
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');
Upvotes: 0
Reputation: 5292
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.
Upvotes: 2
Reputation: 3822
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 :/
Upvotes: 1