I am facing a particular behavior of this object and looking for some help to understand how it works under the hood.
Two snippets:
- Standalone module, running this file as:
node first.js
// first.js
function f1() {
console.log('f1')
this.f2()
}
function f2() {
console.log('f2')
}
module.exports = {
f1,
f2
}
f1();
// Prints:
// f1
// this.f2 is not a function
- Two modules, running this file as:
node second.js
// first.js
function f1() {
console.log('f1')
this.f2()
}
function f2() {
console.log('f2')
}
module.exports = {
f1,
f2
}
// second.js
require('./first.js').f1()
// Prints:
// f1
// f2
- Why is that happening in the first module?
- I guess that functions within module.exports are wrapped into this object when the module is required. Any insight about this?
- Is there any way to make the first snippet working using
bind()
?