Imam Hidayat
Imam Hidayat

Reputation: 158

nodejs - Call a function inside a parent module from a child module

Let's say I have a file called parent.js with the following source code:

var child = require('./child')

var parent = {
    f: function() {
        console.log('This is f() in parent.');
    }
};

module.exports = parent;

child.target();

and a file called child.js with the following source code:

var child = {
    target: function() {
        // The problem is here..
    }
}

module.exports = child;

and I execute the file using the following command:

node parent.js

The thing is, I want to execute f() inside child.js directly without using any require(...) statement. Previously, I'm trying to execute this statement inside target() in child.js:

module.parent.f()

and

module.parent.exports.f()

but it doesn't work. The strange thing is, when I execute console.log(module.parent.exports) inside child.js, the following output appear:

{ f: [Function] }

So why can't I call f() directly?

Upvotes: 4

Views: 4246

Answers (3)

milesholt
milesholt

Reputation: 161

You could also try the following setup, using require.main (module.parent is deprecated) to access the parent functions.

parent.js

var parent = {} 

parent.f = function(){
      console.log('called parent function from child');
    }

module.exports = {
  parent:parent
}

var child = require('./child.js');

child.js

var child = {};
var parent = require.main.exports.parent;

child.f = function(){
  parent.f();
}

//call parent function here
child.f();

module.exports = {
  child:child
}

Upvotes: 1

dave
dave

Reputation: 4104

As an alternative to what Lee Jenkins suggested, you could change your code to this (hard to explain without just showing code)

parent.js

var parent = {
    f: function() {
        console.log('This is f() in parent.');
    }
};

var child = require('./child')(parent);

module.exports = parent;

child.target();

child.js

module.exports = function (parent) {
    return child = {
        target: function() {
            parent.f();
        }
    };
}

Upvotes: 0

Lee Jenkins
Lee Jenkins

Reputation: 2470

You might consider using a callback function:

var child = {
    target: function( callback ) {
        callback();
    }
}

module.exports = child;

Then in parent.js call the target like this:

child.target( parent.f );

Upvotes: 2

Related Questions