Directly calling a function bound to the exports object

I'm reading the cluster.js file of the cluster package and this part confuses me:

fs.readdirSync(__dirname + '/plugins').forEach(function(plugin){
  plugin = plugin.replace('.js', '');
  exports.__defineGetter__(plugin, function(){
    return require('./plugins/' + plugin);
  });
});

I know that you can bind objects or functions to the exports object to expose them to different files, but it seems that it is calling a function already bound to the object. However, I always thought you needed to require the file and access functions that way. What is going on here?

This is realization of lazy loading for plugins. Plugin will be loaded only after first access to module property with his name. __defineGetter__ is the 'syntax sugar' not presented in ECMAScript standard. It binds an object's property to a function to be called when that property is looked up.

If a module sets exports to a single function rather than an arbitrary object, then the result of require will be a function reference which can be called directly (note that a function is actually a type of object and as such can have properties, which can also be functions).

That's not what's going on here, though. At the time the code you've shown is executed, a function called __defineGetter__ has already been defined and attached to exports. Here it's simply being called as a method of exports (presumably because the author didn't feel the need to create a redundant local name for it).

i.e. somewhere along the line there's something like

exports.__defineGetter__ = function(propname, getter) {
...
}

Since it doesn't have a local name, the only way to call it is through exports.

Obviously the purpose of the code here is to allow you to call cluster.nameOfPlugin.method(...) without having to manually require each plugin, while not requiring all the possible plugins to be preloaded; instead only the ones you actually use get loaded.