In this post, lots of answers are there discussing the this
keyword in JavaScript. However, I am still confuse this
in the anonymous function
as following
// MyModule.js
'use strict';
(function(handler) {
// export methods
handler.B = B;
handler.A = A;
function A() {
console.log(this);
console.log('function A is invoked...');
}
function B() {
console.log(this);
console.log('function B is invoked...');
try {
A();
this.A();
} catch (err) {
console.log('Exception is ' + err);
}
}
})(module.exports);
// test.js
var myModule = require('MyModule.js');
myModule.B();
Output: (Running under Node.js)
{ B: [Function: B], A: [Function: A] }
function B is invoked...
undefined
function A is invoked...
{ B: [Function: B], A: [Function: A] }
function A is invoked...
The output indicates the function A
are in two different scopes. Am I right? Why there are two scopes for function A
?
As we know, the this
is related to the scope. And the this
in the anonymous function of MyModule
is undefined
. According to the output, one of the scope of function A
is undefined
, the other is { B: [Function: B], A: [Function: A] }
. What the difference between them?