When I type this in node.js, I get undefined
.
var testContext = 15;
function testFunction() {
console.log(this.testContext);
}
testFunction();
=>undefined
Without var
keyword, it passes (=>15). It's working in the Chrome console (with and without var
keyword).
The key difference is that all modules (script files) in Node.js are executed in their own closure while Chrome and other browsers execute all script files directly within the global scope.
This is mentioned in the Globals documentation:
The
var
s you declare in a Node module will be isolated to one of these closures, which is why you have to export members for other modules to reach them.Though, when calling a
function
without a specific context, it will normally be defaulted to the global object -- which is conveniently calledglobal
in Node.And, without the
var
to declare it,testContext
will default to being defined as a global.As mentioned in the document
So, it is going to be different as the
var testContext
is in module context and the context of this isglobal
.You can alternatively, use:
It doesn't work in Node when using
var
becausetestContext
is a local of the current module. You should reference it directly:console.log(testContext);
.When you don't type
var
, what happens is thattestContext
is now a global var in the entire Node process.In Chrome (or any other browser - well, I'm unsure about oldIE...), it doesn't matter if you use
var
or not in your example,testContext
will go to the global context, which iswindow
.By the way, the "global context" is the default
this
of function calls in JS.I believe the problem has to do with the
this
key word. If you doconsole.log(this)
you will see that testContext is not defined. You may want to try: