How is the require object defined inside the node.js global work required?

OK, I'm a little confused.

If you open a node window and type this.require

, you get:

[Function: require]
resolve: [Function],
main: undefined,
extensions:
{ '.js': [Function],
  '.json': [Function],
  '.node': [Function] },
registerExtension: [Function],
cache: {} }

      

This means that the function require(args)

was created, for examplerequire=function(){return resultOfOperation}

THEN someone went ahead and said: require.cache={}

I'm fine with all of this, but is the cache object any use of the function require(args)

? requirejs sources don't mention object cache at all, so I'm wondering if I'm running into a different module loader, or if that's just what nodejs uses to track different behavior.

Question: "Can / (how can) a function that has been assigned additional properties, access these properties from within the executable body of the code?" (preferably without knowing the superior function)

Note I understand that this is probably just written to the engine in C ++, I'm just curious to see if people can think of a way to do this in javascript

+3


source to share


2 answers


First, there seems to be some kind of confusion. Node is require

not RequireJS . These are two completely different things.

To learn more about the Node modular system, here are the related docs . Here are the docs on require .

To answer your second question, functions in javascript are objects. One way to do something like the one above:



var foo = function() {
    console.log(foo.cache);
};

foo.cache = {
    bar: 1
};

foo();
// Outputs { bar: 1 }

      

Another way is using the deprecated one arguments.callee

(so don't do this at home):

var foo = function() {
    console.log(arguments.callee.cache);
};

foo.cache = {
    bar: 1
};

foo();
// Outputs { bar: 1 }

      

+4


source


Your last question:

Can / (how can) a function that has been assigned additional properties access those properties from within the executable body of code?

You can use the global function name. for example

var myFunc = function() {
    console.log(myFunc.a++);
}
myFunc.a = 1;
myFunc();
myFunc();

      

Will output



1
2

      

Now, your other question

I'm fine with all of this, but is the cache object of any use to the require (args) function?

Yes, require.cache is used, so when you load the same module twice, it returns the same object and doesn't actually load the script. Check out the node.js documentation at require.cache

: http://nodejs.org/api/globals.html#globals_require_cache

+4


source







All Articles