0

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.

Troskyvs
  • 5,653
  • 3
  • 23
  • 71
  • That IIFE doesn't make any sense at all. The `module` parameter is obviously `undefined` if you pass nothing in. – Bergi Aug 11 '16 at 03:41

1 Answers1

2

It's said that nodejs, when executing a js file, will bind "this" to module context

Yes No, it's bound to exports. If you put

console.log(this === module.exports); // or just `exports`

inside your file, it will log true.

when calling function with global scope

No. The this value in the module scope has nothing to do with functions or how they are called. In sloppy mode, the this value in a function that is called plainly will be the global object, but that's not the same as the module object.

function father() {
    console.log(this === global);
}
father(); // true
Community
  • 1
  • 1
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • Seems still doesn't work, see my updated post above. console.log(this === module); prints a "false" in my test. – Troskyvs Aug 11 '16 at 04:07
  • Ooops, I thought the thing you had read was right. Where is exactly was it said? See my update. – Bergi Aug 11 '16 at 04:11
  • I tried what you suggested, but still [ function h(){this.a='abc';} h() console.log(module.exports.a);] will print "undefined". See my last update. Why modules.exports doesn't get updated by h()? – Troskyvs Aug 11 '16 at 10:14
  • Because `module.exports` is not the global object. `this` in a function scope (inside `h`) is something very different than the `this` in the module scope (outside `h`). – Bergi Aug 11 '16 at 10:35