Maqsud Mallick
Maqsud Mallick

Reputation: 63

How do you actually call a nested function while extending modules in nodejs?

I basically tried extending modules with two different modules

1st-

var exports=exports.module={};
exports.tutorial= function(){
    console.log('Raj is king');
};

2nd module

var tutor= require('./Tutorial.js');
exports.NodeTutorial= function(){
    console.log('Node Tutorial');
    function pTutor()
    {
        var putor=tutor;
        putor.tutorial();
    }

};

and finally tried to use these modules with a main.js file

var Addition= require('./NodeTutorial.js');
Addition.NodeTutorial();
Addition.NodeTutorial.pTutor();

However when I tried to execute the code i got the msg Type Error: Addition.NodeTutorial.pTutor is not a function

Upvotes: 0

Views: 56

Answers (1)

Quentin
Quentin

Reputation: 943571

You can't.

pTutor is locally scoped to the function it is declared within. It is not accessible outside that function.

If you want it to be a property of that function, then you need to make it a property.

var tutor = require('./Tutorial.js');
exports.NodeTutorial = function() {
    console.log('Node Tutorial');
}
exports.NodeTutorial.pTutor = function pTutor() {
    var putor = tutor;
    putor.tutorial();
};

Note that while it is possible to attach properties to functions (jQuery does it so you can call, for example both jQuery(...) and jQuery.ajax(...)) it usually results in a confusing API and is best avoided.

Upvotes: 1

Related Questions