Reputation: 1518
ok, I'm kind of stumped.
If you open up 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 as let's say, require=function(){return resultOfOperation}
THEN someone went ahead and said, require.cache={}
I'm fine with all that, but is the cache object of any use to the require(args)
function? the requirejs sources makes no mention of a cache object at all, so I'm wondering if I'm running into a different module loader or if this is just something that nodejs uses to track some other behavior.
Question is, "Can/(How can) a function that has been assigned additional properties access those properties from within the executing body of code?" (preferably without knowledge of a superior function)
Note, I understand that this is possibly just written into the engine in c++, I'm just interested to see whether people can think of a way to do this in javascript
Upvotes: 3
Views: 1331
Reputation: 39261
First off, there seems to be some confusion. Node's require
is not RequireJS. They are two completely different things.
To learn more about node's module system, here are the relevant docs. Here are docs on require.
To answer your second question, functions in javascript are objects. One way to accomplish something like what you describe above:
var foo = function() {
console.log(foo.cache);
};
foo.cache = {
bar: 1
};
foo();
// Outputs { bar: 1 }
Another way uses the deprecated 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 }
Upvotes: 4
Reputation: 15889
Your last question:
Can/(How can) a function that has been assigned additional properties access those properties from within the executing body of code?
You can use the global name of the function. 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 that, but is the cache object of any use to the require(args) function?
Yes, require.cache is used so when you load twice the same module, it returns the same object and doesn't really load the script again. Check out node.js documentation on require.cache
: http://nodejs.org/api/globals.html#globals_require_cache
Upvotes: 4