It's said that nodejs, when executing a js file, will bind this
to module context when calling function with global scope, like this:
function father(){
this.id=10
}
father();
console.log(module.id);
It actually prints ".", not "10" as I expected. If module is the keyword to visit, I did try this:
(function (exports, require, module, __filename, __dirname) {
father();
console.log(module.id);
})()
But this time, it throws out an exception in the line of console.log(module.id)
, saying
"TypeError: Cannot read property 'id' of undefined.
Finally, I tried this:
console.log(this===module);
console.log(this===global);
function f1(){console.log(this===module);}
function f2(){console.log(this===global);}
function g1(){
return function(){console.log(this===module);};
}
function g2(){
return function(){console.log(this===global);};
}
f1();
f2();
g1()();
g2()();
Well it prints:
false
false
false
true
false
true
Not the same as 1st answer suggested. So I wonder how can I use "module" keyword inside a js file, that's executed by Nodejs?
And last try:
function h(){this.a='abc';}
h()
console.log(module.exports.a);
I expect to print "abc", but still it prints "undefined"
Thanks.